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?✗ Incorrect
Kotlin requires all enum cases to be handled in a
when expression or an else branch must be present. Missing cases cause a compile error.Which keyword is used to define an enum in Kotlin?
✗ Incorrect
The
enum keyword defines an enum class in Kotlin.Why might you prefer an exhaustive
when over using else?✗ Incorrect
Exhaustive
when forces you to handle every enum case explicitly, reducing bugs.What type of Kotlin construct is best suited for representing a fixed set of constants?
✗ Incorrect
An
enum class is designed to represent a fixed set of constants.If you add a new value to an enum, what must you do to keep your
when expressions exhaustive?✗ Incorrect
You must update all
when expressions to handle the new enum value to keep them exhaustive.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.