枚举类
枚举类的最基本的应用场景是实现类型安全的枚举:
1. enum class Direction {
2. NORTH, SOUTH, WEST, EAST
3. }
每个枚举常量都是一个对象。枚举常量以逗号分隔。
因为每一个枚举都是枚举类的实例,所以可以这样初始化:
1. enum class Color(val rgb: Int) {
2. RED(0xFF0000),
3. GREEN(0x00FF00),
4. BLUE(0x0000FF)
5. }
匿名类
枚举常量可以声明其带有相应方法以及覆盖了基类方法的自身匿名类 。
1. enum class ProtocolState {
2. WAITING {
3. override fun signal() = TALKING
4. },
6. TALKING {
7. override fun signal() = WAITING
8. };
10. abstract fun signal(): ProtocolState
11. }
如果枚举类定义任何成员,那么使用分号将成员定义与常量定义分隔开。
在枚举类中实现接口
一个枚举类可以实现接口(但不能从类继承),可以为所有条目提供统一的接口成员实现,也可以在相应匿名类中为每个条目提供各自的实现。 只需将想要实现的接口添加到枚举类声明中即可,如下所示:
1. import java.util.function.BinaryOperator
2. import java.util.function.IntBinaryOperator
4. //sampleStart
5. enum class IntArithmetics : BinaryOperator<Int>, IntBinaryOperator {
6. PLUS {
7. override fun apply(t: Int, u: Int): Int = t + u
8. },
9. TIMES {
10. override fun apply(t: Int, u: Int): Int = t * u
11. };
13. override fun applyAsInt(t: Int, u: Int) = apply(t, u)
14. }
15. //sampleEnd
17. fun main() {
18. val a = 13
19. val b = 31
20. for (f in IntArithmetics.values()) {
21. println("$f($a, $b) = ${f.apply(a, b)}")
22. }
23. }
All enum classes implement the Comparable interface by default. Constants in the enum class are defined in the natural order. For more information, see Ordering.
使用枚举常量
Kotlin 中的枚举类也有合成方法用于列出定义的枚举常量以及通过名称获取枚举常量。这些方法的签名如下(假设枚举类的名称是 EnumClass):
1. EnumClass.valueOf(value: String): EnumClass
2. EnumClass.values(): Array<EnumClass>
Below is an example of these methods in action:
1. enum class RGB { RED, GREEN, BLUE }
3. fun main() {
4. for (color in RGB.values()) println(color.toString()) // prints RED, GREEN, BLUE
5. println("The first color is: ${RGB.valueOf("RED")}") // prints "The first color is: RED"
6. }
如果指定的名称与类中定义的任何枚举常量均不匹配, valueOf() 方法会抛出 IllegalArgumentException 异常。
可以使用 enumValues() 与 enumValueOf() 函数以泛型的方式访问枚举类中的常量:
1. enum class RGB { RED, GREEN, BLUE }
3. inline fun <reified T : Enum<T>> printAllValues() {
4. print(enumValues<T>().joinToString { it.name })
5. }
7. printAllValues<RGB>() // 输出 RED, GREEN, BLUE
For more information about inline functions and reified type parameters, see Inline functions.
In Kotlin 1.9.0, the entries property is introduced as a replacement for the values() function. The entries property returns a pre-allocated immutable list of your enum constants. This is particularly useful when you are working with collections and can help you avoid performance issues.
For example:
1. enum class RGB { RED, GREEN, BLUE }
3. fun main() {
4. for (color in RGB.entries) println(color.toString())
5. // prints RED, GREEN, BLUE
6. }
每个枚举常量也都具有这两个属性:name 与 ordinal, 用于在枚举类声明中获取其名称与(自 0 起的)位置:
1. enum class RGB { RED, GREEN, BLUE }
3. fun main() {
4. //sampleStart
5. println(RGB.RED.name) // prints RED
6. println(RGB.RED.ordinal) // prints 0
7. //sampleEnd
8. }

