简书链接:kotlin枚举的简单用法
文章字数:177,阅读全文大约需要1分钟

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class EnumKotlin {

enum class ProtocolState {
WAITING {
override fun fetchAlias() = "my alias is waiting"
},

TALKING {
override fun fetchAlias() = "my alias is talking"
override fun fetchId() = 1;
};


abstract fun fetchAlias(): String
open fun fetchId(): Int {
return 0;
}
}

enum class Color(val rgb: Int) {
RED(0xFF0000),
GREEN(0x00FF00),
BLUE(0x0000FF)
}

enum class Direction {
NORTH, SOUTH, WEST, EAST
}
}


枚举类必须放在已经定义的类里面 或自己直接声明为一个kotlin枚举类, 且不能定义在 方法里面 , 如果kotlin文件没有定义类名,直接放到里面也是不行的除非你就把它作为枚举类

1
2
3
var value = EnumKotlin.Color.BLUE.rgb
println("enum declared order:$ordinal enum value :${Integer.toHexString(value)}")
println("enum protocol name ${alias} ID:${EnumKotlin.ProtocolState.TALKING.fetchId()}")

测试结果:

1
2
enum declared order:2 enum value :ff
enum protocol name my alias is talking ID:1