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
}
相关推荐
FunnySaltyFish19 小时前
什么?Compose 把 GapBuffer 换成了 LinkBuffer?
算法·kotlin·android jetpack
Kapaseker1 天前
Compose 进阶—巧用 GraphicsLayer
android·kotlin
Kapaseker2 天前
实战 Compose 中的 IntrinsicSize
android·kotlin
A0微声z4 天前
Kotlin Multiplatform (KMP) 中使用 Protobuf
kotlin
alexhilton4 天前
使用FunctionGemma进行设备端函数调用
android·kotlin·android jetpack
lhDream5 天前
Kotlin 开发者必看!JetBrains 开源 LLM 框架 Koog 快速上手指南(含示例)
kotlin
RdoZam5 天前
Android-封装基类Activity\Fragment,从0到1记录
android·kotlin
Kapaseker5 天前
研究表明,开发者对Kotlin集合的了解不到 20%
android·kotlin
糖猫猫cc6 天前
Kite:两种方式实现动态表名
java·kotlin·orm·kite
如此风景6 天前
kotlin协程学习小计
android·kotlin