Recall & Review
beginner
What is a sealed class in Kotlin?A sealed class is a special kind of class that restricts which other classes can inherit from it. It helps to define a closed set of subclasses, making the hierarchy controlled and known at compile time.Click to reveal answer
intermediate
Why use sealed classes instead of open classes?
Sealed classes limit subclassing to a fixed set of types, which helps the compiler check when all cases are handled, especially in
when expressions. Open classes allow unlimited subclassing, which can lead to less safe code.Click to reveal answer
intermediate
How do sealed classes improve
when expressions?When you use a sealed class in a <code>when</code> expression, the compiler knows all possible subclasses. This means you don't need an <code>else</code> branch if you cover all subclasses, making your code safer and clearer.Click to reveal answer
beginner
Can sealed classes have subclasses in other packages?
No. All direct subclasses of a sealed class must be declared in the same package or the same file as the sealed class. This restriction keeps the hierarchy closed and controlled.Click to reveal answer
beginner
Example: Define a sealed class
Shape with subclasses Circle and Rectangle.sealed class Shape {
data class Circle(val radius: Double) : Shape()
data class Rectangle(val width: Double, val height: Double) : Shape()
}Click to reveal answer
What is a key feature of sealed classes in Kotlin?
✗ Incorrect
Sealed classes restrict direct subclassing to the same package or file, ensuring a closed set of subclasses.
Why does Kotlin allow omitting the
else branch in a when expression with sealed classes?✗ Incorrect
The compiler knows all subclasses of a sealed class, so it can check if all cases are covered without needing an
else.Which of these is NOT true about sealed classes?
✗ Incorrect
Direct subclasses of sealed classes can be declared in the same package or the same file but do not have to be in the same file (since Kotlin 1.5).
What keyword is used to declare a sealed class in Kotlin?
✗ Incorrect
The keyword
sealed is used to declare a sealed class.Which of the following is a benefit of using sealed classes?
✗ Incorrect
Sealed classes provide better control over class hierarchies and help write safer code by restricting subclassing.
Explain what a sealed class is and why it is useful in Kotlin.
Think about how sealed classes help the compiler know all possible subclasses.
You got /4 concepts.
Describe how sealed classes improve safety and readability when using
when expressions.Focus on the relationship between sealed classes and exhaustive checks.
You got /4 concepts.