0
0
Kotlinprogramming~5 mins

Enum with when exhaustive check in Kotlin - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is an enum in Kotlin?
An enum in Kotlin is a special class that represents a fixed set of constants. It helps group related values under one type, like days of the week or directions.
Click to reveal answer
beginner
What does it mean for a when expression to be exhaustive in Kotlin?
A when expression is exhaustive when it covers all possible cases of the input, so Kotlin knows no other case can happen. This means you don't need an else branch.
Click to reveal answer
intermediate
How does Kotlin ensure when is exhaustive when used with enums?
When you use a when expression with an enum, Kotlin requires you to handle all enum constants. If you miss one, the code won't compile unless you add an else branch.
Click to reveal answer
intermediate
Why is using an exhaustive when with enums helpful?
It helps catch errors early by making sure you handle every possible enum value. This avoids bugs where some cases are forgotten and improves code safety.
Click to reveal answer
beginner
Show a simple Kotlin enum and an exhaustive when expression example.
Example:<br><pre>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"
}</pre>
Click to reveal answer
What happens if you miss an enum case in a when expression without an else branch?
AThe code will not compile.
BThe code will compile but throw an error at runtime.
CThe missing case will be ignored silently.
DKotlin will automatically add the missing case.
Which keyword is used to define an enum in Kotlin?
Aclass
Benum
Cobject
Dsealed
Why might you prefer an exhaustive when over using else?
ATo allow missing cases without errors.
BTo make the code shorter.
CTo ensure all cases are explicitly handled.
DTo avoid using enums.
What type of Kotlin construct is best suited for representing a fixed set of constants?
Afun
Bdata class
Cinterface
Denum class
If you add a new value to an enum, what must you do to keep your when expressions exhaustive?
AAdd a new case for the new enum value in all <code>when</code> expressions.
BNothing, Kotlin updates them automatically.
CRemove the <code>when</code> expressions.
DAdd an <code>else</code> branch to all <code>when</code> expressions.
Explain what an exhaustive when expression is and why it is useful when working with enums in Kotlin.
Think about how Kotlin checks all enum values are handled.
You got /4 concepts.
    Describe how Kotlin enforces handling all enum cases in a when expression and what happens if a case is missing.
    Focus on Kotlin's compile-time checks.
    You got /3 concepts.