如何在 Kotlin 定义非序数枚举?

我想定义一个不是序数的枚举,例如:

enum class States(value: Int) {
STATE_A(4),
STATE_B(5),
STATE_C(7),
STATE_D(12)
}

如何得到每个项目的值? 例如,国家应该返回 7

52809 次浏览

You should define value as property (val) not as constructor parameter. After that it becomes accessible:

enum class States(val value: Int) {
STATE_A(1),
STATE_B(2),
STATE_C(3),
STATE_D(4)
}
...
println(States.STATE_C.value) // prints 3

Also consider to use ordinal, which may be suitable in your case:

enum class States {
STATE_A,
STATE_B,
STATE_C,
STATE_D
}
...
println(States.STATE_C.ordinal + 1) // prints 3

If you go with that approach, be careful - any change of States order can break your code.