Recall & Review
beginner
What is a sealed class in Kotlin?A sealed class is a special kind of class that restricts which classes can inherit from it. All subclasses must be declared in the same file, making the type hierarchy fixed and known at compile time.Click to reveal answer
beginner
Why does Kotlin require exhaustive checks with
when expressions on sealed classes?Because the compiler knows all possible subclasses of a sealed class, it can check if a
when expression covers all cases. This helps avoid missing cases and makes the code safer.Click to reveal answer
beginner
How do you make a
when expression exhaustive in Kotlin?You include all possible subclasses of the sealed class as branches in the <code>when</code> expression. If all cases are covered, the compiler treats it as exhaustive without needing an <code>else</code> branch.Click to reveal answer
intermediate
What happens if a <code>when</code> expression on a sealed class is not exhaustive?The Kotlin compiler will show an error or warning if the <code>when</code> expression does not cover all subclasses of the sealed class and lacks an <code>else</code> branch, forcing you to handle all cases.Click to reveal answer
beginner
Example: Given a sealed class
Shape with subclasses Circle and Square, write an exhaustive when expression to calculate area.sealed class Shape
class Circle(val radius: Double) : Shape()
class Square(val side: Double) : Shape()
fun area(shape: Shape): Double = when(shape) {
is Circle -> Math.PI * shape.radius * shape.radius
is Square -> shape.side * shape.side
}Click to reveal answer
What is the main benefit of using sealed classes with
when in Kotlin?✗ Incorrect
Sealed classes let the compiler know all subclasses, so it can check that
when expressions cover all cases.If a
when expression on a sealed class misses a subclass, what happens?✗ Incorrect
The Kotlin compiler forces you to handle all subclasses or provide an
else branch.Where must subclasses of a sealed class be declared?
✗ Incorrect
All subclasses of a sealed class must be declared in the same file to keep the hierarchy fixed.
Which keyword is used to declare a sealed class in Kotlin?
✗ Incorrect
The
sealed keyword declares a sealed class.Can a sealed class have non-sealed subclasses?
✗ Incorrect
Subclasses can be regular classes but must be declared in the same file as the sealed class.
Explain what a sealed class is and why it helps with
when expressions in Kotlin.Think about how knowing all options helps the compiler.
You got /4 concepts.
Describe how to write an exhaustive
when expression for a sealed class and what happens if you miss a case.Consider the compiler's role in checking completeness.
You got /4 concepts.