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
}
相关推荐
Android-Flutter13 小时前
Android 内存泄漏详解
android·kotlin
Android-Flutter14 小时前
android Handler , Looper , Message , MessageQueue 详解
android·kotlin
阿pin16 小时前
Android随笔-kotlin Flow
android·kotlin·flow
松仔log16 小时前
JetPack——Hilt
android·java·开发语言·kotlin
chjif17 小时前
Android 设备管控开发实战:常见保活与拉活方案怎么组合,实测能到什么程度?
android·kotlin
XiaoLeisj17 小时前
Kotlin Flow 常用操作符:数据变换 map、filter、onEach,时间控制 debounce、sample,终端聚合 reduce、fold
android·kotlin·android jetpack·协程·响应式编程·flow
Kapaseker18 小时前
小白都看得懂的 Skill 教程 - 创建第一个 Skill
android·kotlin·vibecoding
zhangphil18 小时前
Android BitmapFactory实现AOSP ContentResolver.loadThumbnail快速取小缩略图,Kotlin
android·kotlin
Android-Flutter18 小时前
android 生命周期管理,继承Activity,不是AppCompatActivity
android·kotlin
XiaoLeisj2 天前
Kotlin Flow:冷流收集、并行订阅、emit 推送、delay 延迟、collect 全量收集与 collectLatest 的实时数据处理
android·kotlin·android jetpack·协程·flow