Kotlin Enumeration
The most basic usage of an enumeration class is to implement a type-safe enumeration.
Enumeration constants are separated by commas, and each enumeration constant is an object
enum class Color{
RED,BLACK,BLUE,GREEN,WHITE
}
Enumeration initialization
Each enumeration is an instance of the enumeration class, they can be initialized
enum class Color(val rgb: Int) {
RED(0xFF0000),
GREEN(0x00FF00),
BLUE(0x0000FF)
}
The default name is the enumerated character name, and the value starts from 0. If you need to specify a value, you can use its constructor
enum class Shape(value:Int){
ovel(100),
rectangle(200)
}
Enumerations also support to declare their own anonymous classes and corresponding methods, as well as to override the methods of the base class. Such as
enum class ProtocolState {
WAITING {
override fun signal() = TALKING
},
TALKING {
override fun signal() = WAITING
};
abstract fun signal(): ProtocolState
}
If the enumeration class defines any members, use a semicolon to separate the enumeration constant definition in the member definition
Use enum constants
The enumeration class in Kotlin has a synthetic method that allows it to traverse the defined enumeration constant and obtain the enumeration constant by its name
EnumClass.valueOf(value: String): EnumClass // 转换指定 name 为枚举值,若未匹配成功,会抛出IllegalArgumentException
EnumClass.values(): Array<EnumClass> // 以数组的形式,返回枚举值
Get enumeration related information:
val name: String //获取枚举名称
val ordinal: Int //获取枚举值在所有枚举数组中定义的顺序
Instance
enum class Color{
RED,BLACK,BLUE,GREEN,WHITE
}
fun main(args: Array<String>) {
var color:Color=Color.BLUE
println(Color.values())
println(Color.valueOf("RED"))
println(color.name)
println(color.ordinal)
}
Since Kotlin 1.1, you can use the enumValues<T>()
and enumValueOf<T>()
function to access the constants in the enumeration class in a generic way
enum class RGB { RED, GREEN, BLUE }
inline fun <reified T : Enum<T>> printAllValues() {
print(enumValues<T>().joinToString { it.name })
}
fun main(args: Array<String>) {
printAllValues<RGB>() // 输出 RED, GREEN, BLUE
}