Enum with when exhaustive check in Kotlin - Time & Space Complexity
We want to understand how the time needed to run code changes when using an enum with a when statement that covers all cases.
How does the number of enum values affect how long the code takes to run?
Analyze the time complexity of the following code snippet.
enum class Direction { NORTH, SOUTH, EAST, WEST }
fun describeDirection(dir: Direction): String = when(dir) {
Direction.NORTH -> "Going north"
Direction.SOUTH -> "Going south"
Direction.EAST -> "Going east"
Direction.WEST -> "Going west"
}
This code returns a description string for each direction using an exhaustive when statement on an enum.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Checking the enum value once in the when statement.
- How many times: Exactly once per function call, no loops or recursion.
The function checks the input enum value once and returns the matching string.
| Input Size (number of enum values) | Approx. Operations |
|---|---|
| 4 | 1 check per call |
| 10 | 1 check per call |
| 100 | 1 check per call |
Pattern observation: The time to run does not grow with the number of enum values because the when statement directly matches the input.
Time Complexity: O(1)
This means the function takes the same amount of time no matter how many enum values there are.
[X] Wrong: "The time grows with the number of enum values because the when checks each case one by one."
[OK] Correct: The Kotlin compiler optimizes the when on enums to a fast lookup, so it does not check each case one by one at runtime.
Understanding how enum and when statements work helps you write clear and efficient code, a skill valued in many coding tasks and interviews.
"What if we replaced the enum with a list of strings and used when to check each string? How would the time complexity change?"