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
}
相关推荐
前行的小黑炭1 小时前
Android :如何快速让布局适配手机和平板?
android·java·kotlin
Yang-Never5 小时前
Kotlin协程 -> Job.join() 完整流程图与核心源码分析
android·开发语言·kotlin·android studio
XeonYu6 小时前
Kotlin 协程之 突破 Flow 限制:Channel 与 Flow 的结合之道
kotlin·coroutine·channelflow·callbackflow·receiveasflow·consumeasflow
XeonYu10 小时前
Kotlin 协程之 Flow 的理解使用及源码解析
kotlin·flow·coroutine
低调小一17 小时前
Swift 语法学习指南 - 与 Kotlin 对比
微信·kotlin·swift
叽哥1 天前
Kotlin学习第 3 课:Kotlin 流程控制:掌握逻辑分支与循环的艺术
android·java·kotlin
用户091 天前
Gradle 现代化任务依赖方案
android·kotlin
前行的小黑炭1 天前
Android 协程的使用:结合一个环境噪音检查功能的例子来玩玩
android·java·kotlin
Android-Flutter2 天前
kotlin - 平板分屏,左右拖动,2个Activity计算宽度,使用ActivityOptions、Rect(三)
android·kotlin
前行的小黑炭3 天前
Android :为APK注入“脂肪”,论Android垃圾代码在安全加固中的作用
android·kotlin