Enum class declaration in Kotlin - Time & Space Complexity
Let's see how the time it takes to run code changes when we use an enum class in Kotlin.
We want to know how the program's work grows as we use more enum values.
Analyze the time complexity of the following code snippet.
enum class Direction {
NORTH, SOUTH, EAST, WEST
}
fun printDirections() {
for (dir in Direction.values()) {
println(dir)
}
}
This code defines an enum with four directions and prints each one.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through all enum values using
Direction.values(). - How many times: Once for each enum constant (4 times here).
As the number of enum values grows, the loop runs once for each value.
| Input Size (n) | Approx. Operations |
|---|---|
| 4 | 4 (one print per direction) |
| 10 | 10 |
| 100 | 100 |
Pattern observation: The work grows directly with the number of enum values.
Time Complexity: O(n)
This means the time to run grows in a straight line with the number of enum entries.
[X] Wrong: "Enum classes run in constant time no matter how many values they have."
[OK] Correct: Because looping through all enum values takes time proportional to how many values exist.
Understanding how enum classes work helps you explain simple loops and collections clearly, a skill useful in many coding discussions.
"What if we replaced the loop with a function that looks up a single enum value by name? How would the time complexity change?"