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. It helps represent restricted class hierarchies, making code safer and easier to understand.Click to reveal answer
intermediate
Why use sealed classes instead of enums?
Sealed classes can hold state and have multiple properties, unlike enums which are limited to fixed constants. Sealed classes allow more complex data and behavior.
Click to reveal answer
beginner
How do you declare a sealed class in Kotlin?Use the keyword <code>sealed</code> before <code>class</code>. For example: <br><code>sealed class Result</code>Click to reveal answer
intermediate
Can sealed classes have subclasses outside their file?
No. All subclasses of a sealed class must be declared in the same file. This restriction helps the compiler know all possible subclasses.Click to reveal answer
intermediate
How does a sealed class improve <code>when</code> expressions?When you use a sealed class in a <code>when</code> expression, the compiler knows all subclasses and can enforce that all cases are handled, making the code safer.Click to reveal answer
What keyword do you use to declare a sealed class in Kotlin?
✗ Incorrect
The keyword
sealed declares a sealed class.Where must subclasses of a sealed class be declared?
✗ Incorrect
All subclasses must be declared in the same file to keep the hierarchy closed.
Which of these is a benefit of using sealed classes?
✗ Incorrect
Sealed classes help the compiler check that all cases are handled in when expressions.
Can sealed classes hold state or properties?
✗ Incorrect
Sealed classes can have properties and hold state, unlike enums.
Which of these is NOT true about sealed classes?
✗ Incorrect
Sealed classes do NOT allow unlimited subclassing; subclasses must be in the same file.
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 /3 concepts.
Describe how sealed classes improve the use of when expressions in Kotlin.
Consider what happens if you forget to handle a subclass in a when expression.
You got /3 concepts.