August 2017
Intermediate to advanced
440 pages
10h
English
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 ...
Read now
Unlock full access