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?"
Practice
when expression require when used with an enum class?Solution
Step 1: Understand enum and when usage
Kotlin enums define fixed values. Thewhenexpression can check these values.Step 2: Check compiler requirements for exhaustive when
Kotlin requires all enum cases to be handled inwhento be exhaustive, avoiding missing cases.Final Answer:
All enum cases must be handled to ensure exhaustive checking. -> Option AQuick Check:
Exhaustive when = all enum cases handled [OK]
- Forgetting to handle all enum values
- Using else unnecessarily when all cases are covered
- Assuming when can't be exhaustive with enums
when expression that exhaustively checks all values of this enum?enum class Direction { NORTH, SOUTH, EAST, WEST }Solution
Step 1: Check all enum values handled
when(dir) { Direction.NORTH -> "N"; Direction.SOUTH -> "S"; Direction.EAST -> "E"; Direction.WEST -> "W" } lists all four enum values with their results, no else needed.Step 2: Verify syntax correctness
when(dir) { Direction.NORTH -> "N"; Direction.SOUTH -> "S"; Direction.EAST -> "E"; Direction.WEST -> "W" } uses correct when syntax with enum constants and returns strings.Final Answer:
when(dir) { Direction.NORTH -> "N"; Direction.SOUTH -> "S"; Direction.EAST -> "E"; Direction.WEST -> "W" } -> Option AQuick Check:
All enum cases handled without else = when(dir) { Direction.NORTH -> "N"; Direction.SOUTH -> "S"; Direction.EAST -> "E"; Direction.WEST -> "W" } [OK]
- Using else when all enum cases are handled
- Missing some enum values in when
- Using wrong types in when branches
enum class Light { RED, GREEN, YELLOW }
fun signalMessage(light: Light) = when(light) {
Light.RED -> "Stop"
Light.GREEN -> "Go"
Light.YELLOW -> "Caution"
}
fun main() {
println(signalMessage(Light.YELLOW))
}Solution
Step 1: Identify the enum value passed
The function is called withLight.YELLOW.Step 2: Match enum value in when expression
The when expression returns "Caution" forLight.YELLOW.Final Answer:
Caution -> Option CQuick Check:
Light.YELLOW maps to "Caution" [OK]
- Confusing enum values with strings
- Assuming else is needed for exhaustive when
- Expecting compilation error due to missing else
enum class Status { SUCCESS, ERROR, LOADING }
fun getStatusMessage(status: Status) = when(status) {
Status.SUCCESS -> "Done"
Status.ERROR -> "Failed"
}
Solution
Step 1: Check enum cases handled in when
OnlyStatus.SUCCESSandStatus.ERRORare handled;Status.LOADINGis missing.Step 2: Understand Kotlin's exhaustive when requirement
When used as expression, all enum cases must be handled or else an else branch is needed.Final Answer:
Not all enum cases handled in when expression -> Option BQuick Check:
Missing enum case causes compilation error [OK]
- Assuming else is optional when missing enum cases
- Ignoring missing enum values in when
- Thinking function return type causes error
getDayType to use an exhaustive when expression without an else branch?enum class Day { MON, TUE, WED, THU, FRI, SAT, SUN }
fun getDayType(day: Day): String = when(day) {
Day.SAT, Day.SUN -> "Weekend"
Day.MON, Day.TUE, Day.WED, Day.THU, Day.FRI -> "Weekday"
}Solution
Step 1: Analyze current when branches
The branches cover Day.SAT, Day.SUN and Day.MON, Day.TUE, Day.WED, Day.THU, Day.FRI, which includes all seven enum values.Step 2: Verify Kotlin's exhaustive when rules
Kotlin considers thewhenexhaustive if all enum cases are explicitly covered across branches, even when grouped with commas in the same branch. Noelsebranch is needed.Final Answer:
Keep combined branches as is; Kotlin treats it as exhaustive. -> Option DQuick Check:
Grouped coverage of all enum cases = exhaustive without else [OK]
- Thinking combined branches don't count as exhaustive
- Believing you must use separate branches for each enum value
- Unnecessarily adding an else branch
Ready to prove it?
Pass the test and this pattern moves unknown
