Summary - Enums
- Kotlin course
- Beginner
- Lesson 99/116
- 5 min
Combine enum class and when to write a state machine.
Summary - Enums
In this group you learned to declare an enum class, access constants with entries/valueOf/ordinal, add properties and methods, write exhaustive branches with when and loop over entries.
Now it is time to combine them in a small task: define an enum, print its count and its first constant. This is a small sample of a real choice structure.
Practice Count days and print the first
Define an enum class called Day with MON, TUE, WED, THU, FRI. In main first print Day.entries.size, then Day.entries.first().
Starter code
fun main() {
// Define a day type; print the count and the first constant
}Sample solution
enum class Day { MON, TUE, WED, THU, FRI }
fun main() {
println(Day.entries.size)
println(Day.entries.first())
}Expected output
5 MON
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Fill in the blank: get the order
val s = Color.GREEN.____
val s = Color.GREEN.ordinal
Explanation: ordinal gives the constant's order.
2 Match tool to purpose
| Term | Meaning |
|---|---|
enum class |
Declaration |
entries |
All constants |
when |
All branches |
ordinal |
Order |
3 Which is true about enum constants?
- Enum constants are mutable
- Enums only hold numbers
- Enum constants are fixed Correct answer
- Enums cannot implement interfaces
Explanation: Each constant is a single object; it does not change after compile.