Enum classes
An enumerated type (enum) is a data type consisting of a set of named values. To define an enum type, we need to add the enum keyword to the class declaration header:
enum class Color {
RED,
ORANGE,
BLUE,
GRAY,
VIOLET
}
val favouriteColor = Color.BLUE To parse a string into enum, use the valueOf method (like in Java):
val selectedColor = Color.valueOf("BLUE")
println(selectedColor == Color.BLUE) // prints: true Or you can use the Kotlin helper method:
val selectedColor = enumValueOf<Color>("BLUE")
println(selectedColor == Color.BLUE) // prints: true To display all values in the Color enum, use the values function (like in Java):
for (color in Color.values()) {
println("name: ${it.name}, ordinal: ${it.ordinal}")
} Or you can use the Kotlin enumerateValues helper method:
for (color in enumValues<Color>()) {
println("name: ${it.name}, ordinal: ${it.ordinal}") ...