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
}
相关推荐
Kapaseker15 小时前
Compose 动画 — 显隐的艺术
android·kotlin
赏金术士17 小时前
Retrofit + Kotlin 协程(Android 实战教程)
android·kotlin·retrofit
高林雨露1 天前
kotlin by 和 = 的区别在于【属性委托】和直【接赋值】的差异
kotlin
高林雨露1 天前
Kotlin 的延迟初始化委托属性 by lazy
kotlin
Kapaseker2 天前
我为什么让 Toast 多弹了一次
android·kotlin
赏金术士2 天前
Kotlin Flow 完全指南
android·开发语言·kotlin
帅次2 天前
测试分层:JVM 单测、ViewModel 测试与 Compose UI Test
android·jvm·ui·kotlin·compose·modifier
赏金术士2 天前
Kotlin 习题集 · 高级篇
android·开发语言·kotlin
pengyu3 天前
【Kotlin 协程修仙录 · 金丹境 · 中阶】 | 启动密法:CoroutineStart 四种模式与底层调度玄机
android·kotlin
UXbot3 天前
AI一次生成iOS和Android双端原型功能详解
android·前端·ios·kotlin·交互·swift