Bird
Raised Fist0
Kotlinprogramming~10 mins

Enum with when exhaustive check in Kotlin - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Enum with when exhaustive check
Start
↓
Define enum
↓
Use when with enum
↓
Check all enum cases
↓
All cases covered?
No→Compiler error
Yes↓
Execute matched branch
↓
End
The program defines an enum and uses a when expression to handle all enum values. The compiler checks if all enum cases are covered, ensuring no case is missed.
Execution Sample
Kotlin
enum class Direction { NORTH, SOUTH, EAST, WEST }

fun describe(dir: Direction) = when(dir) {
  Direction.NORTH -> "Up"
  Direction.SOUTH -> "Down"
  Direction.EAST -> "Right"
  Direction.WEST -> "Left"
}
This code defines a Direction enum and a function that returns a string description for each direction using an exhaustive when expression.
Execution Table
StepInput (dir)Condition CheckedBranch TakenOutput
1Direction.NORTHdir == NORTH?Yes"Up"
2Direction.SOUTHdir == NORTH? No; dir == SOUTH?Yes"Down"
3Direction.EASTdir == NORTH? No; dir == SOUTH? No; dir == EAST?Yes"Right"
4Direction.WESTdir == NORTH? No; dir == SOUTH? No; dir == EAST? No; dir == WEST?Yes"Left"
5Direction.UNKNOWN (hypothetical)No matching branchCompiler errorNo output
💡 Execution stops after matching the input direction to a branch; if any enum case is missing, compiler error prevents running.
Variable Tracker
VariableStartAfter 1After 2After 3After 4Final
dirNORTHSOUTHEASTWESTUNKNOWN (hypothetical)N/A
outputN/A"Up""Down""Right""Left"N/A
Key Moments - 2 Insights
Why does the compiler give an error if I forget one enum case in the when expression?
Because the when expression is exhaustive for enums, the compiler checks all enum values are handled (see execution_table row 5). Missing a case causes a compile-time error to prevent unexpected behavior.
What happens if I add an else branch in the when expression?
Adding else makes the when expression non-exhaustive for enums, so the compiler stops checking all enum cases. This can hide missing cases and is not recommended for enums.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what output is produced when dir is Direction.EAST?
A"Up"
B"Right"
C"Down"
D"Left"
💡 Hint
Check execution_table row 3 for dir == EAST and the output column.
At which step does the compiler error occur if a case is missing?
AStep 5
BStep 4
CStep 1
DNo error occurs
💡 Hint
See execution_table row 5 describing the hypothetical missing case and compiler error.
If you add an else branch to the when, what changes in the compiler check?
ACompiler enforces all enum cases still
BCompiler throws runtime error
CCompiler stops enforcing exhaustive check
DCompiler requires more enum cases
💡 Hint
Refer to key_moments second question about else branch effect.
Concept Snapshot
enum class Direction { ... }
fun describe(dir: Direction) = when(dir) {
  Direction.NORTH -> "Up"
  Direction.SOUTH -> "Down"
  Direction.EAST -> "Right"
  Direction.WEST -> "Left"
}

- when with enum must cover all cases
- compiler enforces exhaustive check
- no else needed or allowed for full coverage
Full Transcript
This example shows how Kotlin uses enums with when expressions. The enum Direction has four values. The function describe uses when to return a string for each direction. The compiler checks that all enum cases are handled, so no case is missed. If a case is missing, the compiler gives an error. Adding an else branch disables this check. The execution table shows how each input direction matches a branch and produces output. The variable tracker shows how the input and output change step by step. Key moments explain why exhaustive checks matter and how else affects them. The visual quiz tests understanding of outputs and compiler behavior.

Practice

(1/5)
1. What does the Kotlin when expression require when used with an enum class?
easy
A. All enum cases must be handled to ensure exhaustive checking.
B. Only one enum case needs to be handled.
C. The when expression cannot be used with enums.
D. You must use else even if all enum cases are handled.

Solution

  1. Step 1: Understand enum and when usage

    Kotlin enums define fixed values. The when expression can check these values.
  2. Step 2: Check compiler requirements for exhaustive when

    Kotlin requires all enum cases to be handled in when to be exhaustive, avoiding missing cases.
  3. Final Answer:

    All enum cases must be handled to ensure exhaustive checking. -> Option A
  4. Quick Check:

    Exhaustive when = all enum cases handled [OK]
Hint: Remember: when with enum must cover all cases [OK]
Common Mistakes:
  • Forgetting to handle all enum values
  • Using else unnecessarily when all cases are covered
  • Assuming when can't be exhaustive with enums
2. Which of the following is the correct syntax for a when expression that exhaustively checks all values of this enum?
enum class Direction { NORTH, SOUTH, EAST, WEST }
easy
A. when(dir) { Direction.NORTH -> "N"; Direction.SOUTH -> "S"; Direction.EAST -> "E"; Direction.WEST -> "W" }
B. when(dir) { Direction.NORTH, Direction.SOUTH -> "NS" }
C. when(dir) { "N" -> Direction.NORTH; "S" -> Direction.SOUTH }
D. when(dir) { Direction.NORTH -> "N"; Direction.SOUTH -> "S" }

Solution

  1. 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.
  2. 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.
  3. Final Answer:

    when(dir) { Direction.NORTH -> "N"; Direction.SOUTH -> "S"; Direction.EAST -> "E"; Direction.WEST -> "W" } -> Option A
  4. Quick Check:

    All enum cases handled without else = when(dir) { Direction.NORTH -> "N"; Direction.SOUTH -> "S"; Direction.EAST -> "E"; Direction.WEST -> "W" } [OK]
Hint: List all enum values explicitly for exhaustive when [OK]
Common Mistakes:
  • Using else when all enum cases are handled
  • Missing some enum values in when
  • Using wrong types in when branches
3. What will be the output of this Kotlin code?
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))
}
medium
A. Stop
B. Go
C. Caution
D. Compilation error

Solution

  1. Step 1: Identify the enum value passed

    The function is called with Light.YELLOW.
  2. Step 2: Match enum value in when expression

    The when expression returns "Caution" for Light.YELLOW.
  3. Final Answer:

    Caution -> Option C
  4. Quick Check:

    Light.YELLOW maps to "Caution" [OK]
Hint: Match enum value to when branch to find output [OK]
Common Mistakes:
  • Confusing enum values with strings
  • Assuming else is needed for exhaustive when
  • Expecting compilation error due to missing else
4. This Kotlin code does not compile. What is the error?
enum class Status { SUCCESS, ERROR, LOADING }

fun getStatusMessage(status: Status) = when(status) {
    Status.SUCCESS -> "Done"
    Status.ERROR -> "Failed"
}
medium
A. Missing else branch in when expression
B. Not all enum cases handled in when expression
C. Incorrect enum class declaration
D. Function return type missing

Solution

  1. Step 1: Check enum cases handled in when

    Only Status.SUCCESS and Status.ERROR are handled; Status.LOADING is missing.
  2. 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.
  3. Final Answer:

    Not all enum cases handled in when expression -> Option B
  4. Quick Check:

    Missing enum case causes compilation error [OK]
Hint: Cover all enum values or add else to fix compilation [OK]
Common Mistakes:
  • Assuming else is optional when missing enum cases
  • Ignoring missing enum values in when
  • Thinking function return type causes error
5. Given this enum and function, how can you modify 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"
}
medium
A. Add an else branch to cover any missing cases.
B. Add all enum values explicitly in separate branches without combining.
C. Add a default return statement after when.
D. Keep combined branches as is; Kotlin treats it as exhaustive.

Solution

  1. 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.
  2. Step 2: Verify Kotlin's exhaustive when rules

    Kotlin considers the when exhaustive if all enum cases are explicitly covered across branches, even when grouped with commas in the same branch. No else branch is needed.
  3. Final Answer:

    Keep combined branches as is; Kotlin treats it as exhaustive. -> Option D
  4. Quick Check:

    Grouped coverage of all enum cases = exhaustive without else [OK]
Hint: Comma-grouped enum values in branches make when exhaustive [OK]
Common Mistakes:
  • Thinking combined branches don't count as exhaustive
  • Believing you must use separate branches for each enum value
  • Unnecessarily adding an else branch
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard