Kotlin Enum Classes
The most basic use of an enum class is to implement a type-safe enumeration.
Enum constants are separated by commas, and each enum constant is an object.
enum class Color {
RED, BLACK, BLUE, GREEN, WHITE
}
Enum Initialization
Each enumeration is an instance of the enum class, and they can be initialized:
enum class Color(val rgb: Int) {
RED(0xFF0000),
GREEN(0x00FF00),
BLUE(0x0000FF)
}
The default name is the name of the enum character, and the value starts from 0. If you need to specify a value, you can use its constructor:
enum class Shape(value: Int) {
oval(100),
rectangle(200)
}
Enums also support declaring their own anonymous classes and corresponding methods, as well as overriding methods of the base class. For example:
enum class ProtocolState {
WAITING {
override fun signal() = TALKING
},
TALKING {
override fun signal() = WAITING
};
abstract fun signal(): ProtocolState
}
If the enum class defines any members, use a semicolon to separate the enum constant definitions in the member definition.
Using Enum Constants
Enum classes in Kotlin have synthetic methods that allow iterating over the defined enum constants and retrieving the enum constant by its name.
EnumClass.valueOf(value: String): EnumClass // Converts the specified name to an enum value, throws IllegalArgumentException if no match is found
EnumClass.values(): Array<EnumClass> // Returns the enum values in an array
Get enum-related information:
val name: String // Get the enum name
val ordinal: Int // Get the order of the enum value in the array of all defined enums
Example
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>()
functions to access the constants in an enum 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>() // Outputs RED, GREEN, BLUE
}