Enum values
- Kotlin course
- Beginner
- Lesson 95/116
- 4 min
Learn to access enum members and their values.
Enum values: entries, valueOf, ordinal
entries returns all constants as a list. valueOf("NAME") goes from name to constant. ordinal gives the declaration order of a constant.
val list = Color.entries // [RED, GREEN, BLUE]
val c = Color.valueOf("RED")
println(c.ordinal) // 0entries is the preferred way in Kotlin 2.x; it is an immutable list. valueOf throws on an unknown name; the name must be exact. ordinal starts at 0 and grows with declaration order.
entries vs values
In Kotlin 2.x entries is preferred; it returns an immutable List. The old values() builds a new array on every call.
val a = Color.entries // List<Color>
val b = Color.values() // Array<Color>entries shares the same list every time; it is more efficient. values() appears in old code; use entries in new code. Both return constants in declaration order.
Practice Print constants with their ordinals
Define an enum class called Size with SMALL, MEDIUM, LARGE. Loop over entries and print each constant's name and ordinal.
Starter code
fun main() {
// Define a size type and print each constant's name and order
}Sample solution
enum class Size { SMALL, MEDIUM, LARGE }
fun main() {
for (s in Size.entries) {
println("${s.name} ${s.ordinal}")
}
}Expected output
SMALL 0 MEDIUM 1 LARGE 2
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match method to job
| Term | Meaning |
|---|---|
entries |
All constants |
valueOf |
Find by name |
ordinal |
Order number |
name |
Constant name |
2 Fill in the blank: name to constant
val c = Color.____("RED")
val c = Color.valueOf("RED")
Explanation: valueOf turns a name into a constant.
3 What does Color.GREEN.ordinal return? (Color: RED, GREEN, BLUE)
- The constant name
- Total count
- The order index Correct answer
- The color value
Explanation: ordinal gives the declaration order; GREEN is 1.