Kotlin 枚举类

使用 enum 修饰符;每个枚举常量都是一个对象,枚举常量以逗号分隔

Kotlin 复制代码
// 枚举类
enum class Direction {
    NORTH, SOUTH, WEST, EAST
}

// 每一个枚举都是枚举类的实例,所以可以这样初始化
enum class Color(val rgb: Int) {
    RED(0xFF0000),
    GREEN(0x00FF00),
    BLUE(0x0000FF)
}

枚举常量可以声明其带有相应方法以及覆盖了基类方法的自身匿名类

Kotlin 复制代码
enum class ProtocolState {
    WAITING {
        override fun signal() = TALKING
    },

    TALKING {
        override fun signal() = WAITING
    };
    // 如果枚举类定义任何成员,那么使用分号将成员定义与常量定义分隔开
    abstract fun signal(): ProtocolState
}

一个枚举类可以实现接口(但不能从类继承)

Kotlin 复制代码
enum class IntArithmetics : BinaryOperator<Int>, IntBinaryOperator {
    PLUS {
        override fun apply(t: Int, u: Int): Int = t + u
    },
    TIMES {
        override fun apply(t: Int, u: Int): Int = t * u
    };

    override fun applyAsInt(t: Int, u: Int) = apply(t, u)
}

枚举常量的列举或获取

Kotlin 复制代码
// 假设枚举类的名称是 EnumClass
EnumClass.valueOf(value: String): EnumClass
EnumClass.values(): Array<EnumClass>

enum class RGB { RED, GREEN, BLUE }

fun main() {
    for (color in RGB.values()) println(color.toString()) // prints RED, GREEN, BLUE
    println("The first color is: ${RGB.valueOf("RED")}") // prints "The first color is: RED"

    for (color in RGB.entries) println(color.toString())
    // prints RED, GREEN, BLUE
}

可以使用 enumValues<T>()enumValueOf<T>() 函数以泛型的方式访问枚举类中的常量

Kotlin 复制代码
enum class RGB { RED, GREEN, BLUE }

inline fun <reified T : Enum<T>> printAllValues() {
    print(enumValues<T>().joinToString { it.name })
}

printAllValues<RGB>() // 输出 RED, GREEN, BLUE

每个枚举常量也都具有这两个属性:nameordinal, 用于在枚举类声明中获取其名称与(自 0 起的)位置

Kotlin 复制代码
enum class RGB { RED, GREEN, BLUE }

fun main() {
    println(RGB.RED.name) // prints RED
    println(RGB.RED.ordinal) // prints 0
}
相关推荐
btown2 天前
Kotlin 版 MyBatis-Plus 查询优雅解决方案
kotlin
小二·2 天前
车载数字座舱实战:用魔珐星云打造下一代智能驾乘助手(附 Android/Kotlin 完整代码)
开发语言·kotlin
我命由我123452 天前
Android 开发问题:java.lang.NoSuchMethodError:No virtual method readAllBytes()
android·java·java-ee·kotlin·android studio·android-studio·android runtime
Kapaseker3 天前
你是不是还没用过 select?实战 Kotlin select
android·kotlin
plainGeekDev3 天前
synchronized → Coroutines
android·java·kotlin
唐青枫3 天前
Java Gradle 实战指南:从 Wrapper、Kotlin DSL 到 Spring Boot 多模块构建
java·kotlin·gradle
帅次4 天前
Kotlin Flow 与 StateFlow:UI 单向数据流基础
开发语言·ui·kotlin·stateflow·onlifecycle
Kapaseker5 天前
Sequence 一定比 List 快?等等,我们先从基础讲起
android·kotlin
zhangjin11205 天前
Android Studio创建HelloWorld(kotlin版本)
android·kotlin·android studio
怣疯knight5 天前
kotlin安卓应用打包编译卡死的可能原因
android·kotlin