Enum and range
- Kotlin course
- Beginner
- Lesson 98/116
- 5 min
Learn ranges and iteration with enums.
Enum and range: ordered traversal
You can walk through all constants of an enum in order with a for loop over entries.
for (c in Color.entries) {
println(c)
}
// RED, GREEN, BLUEBecause entries is an immutable list, it does not change during the loop. The order follows the declaration order. You get the same layout every time.
Filtering with the order index
You can pick a subset by using the ordinal of the constants. This is handy for sorting logic.
val firstPair = Color.entries.filter { it.ordinal < 2 }
// [RED, GREEN]filter keeps each constant that meets a condition. it is each constant in the list. This lets you slice subsets by declaration order.
Practice Print the sizes
Define an enum class called Size with SMALL, MEDIUM, LARGE. Loop over entries with a for and print each constant on its own line.
Starter code
fun main() {
// Define a size type and print all constants
}Sample solution
enum class Size { SMALL, MEDIUM, LARGE }
fun main() {
for (s in Size.entries) {
println(s)
}
}Expected output
SMALL MEDIUM LARGE
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match construct to use
| Term | Meaning |
|---|---|
entries |
All constants |
for (c in ...) |
Loop |
ordinal |
Order number |
Color.RED |
One constant |
2 What do you use to walk all constants in order?
- Color.each
- for (c in Color.entries) Correct answer
- Color.loop
- for (c of Color)
Explanation: A for loop over entries does the walk.
3 Fill in the blank: set up the loop
for (c in Color.____) println(c)
for (c in Color.entries) println(c)
Explanation: Color.entries gives you all constants.