Enum Classes
Enum classes are used to model types that represent a finite set of distinct values, such as directions, states, modes, and so forth.
enum class State {
IDLE, RUNNING, FINISHED // 1
}
fun main() {
val state = State.RUNNING // 2
val message = when (state) { // 3
State.IDLE -> "It's idle"
State.RUNNING -> "It's running"
State.FINISHED -> "It's finished"
}
println(message)
}
- Defines a simple enum class with three enum constants. The number of constants is always finite and they are all distinct.
- Accesses an enum constant via the class name.
- With enums, the compiler can infer if a
when
-expression is exhaustive so that you don't need theelse
-case.
Enums may contain properties and methods like other classes, separated from the list of enum constants by a semicolon.
enum class Color(val rgb: Int) { // 1
RED(0xFF0000), // 2
GREEN(0x00FF00),
BLUE(0x0000FF),
YELLOW(0xFFFF00);
fun containsRed() = (this.rgb and 0xFF0000 != 0) // 3
}
fun main() {
val red = Color.RED
println(red) // 4
println(red.containsRed()) // 5
println(Color.BLUE.containsRed()) // 6
println(Color.YELLOW.containsRed()) // 7
}
- Defines an enum class with a property and a method.
- Each enum constant must pass an argument for the constructor parameter.
- Enum class members are separated from the constant definitions by a semicolon.
- The default
toString
returns the name of the constant, here"RED"
. - Calls a method on an enum constant.
- Calls a method via enum class name.
- The RGB values of
RED
andYELLOW
share first bits (FF
) so this prints 'true'.