0
0
Android Kotlinmobile~5 mins

Sealed classes in Android Kotlin - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
Asealed
Bopen
Cabstract
Dfinal
Where must subclasses of a sealed class be declared?
AIn a different module
BAnywhere in the project
CIn a different package
DIn the same file as the sealed class
Which of these is a benefit of using sealed classes?
ACompiler enforces exhaustive when expressions
BAllows subclasses anywhere
CCan be instantiated directly
DNo restrictions on inheritance
Can sealed classes hold state or properties?
ANo, they are like enums with fixed constants
BOnly if marked abstract
CYes, they can have properties and state
DOnly if subclasses are data classes
Which of these is NOT true about sealed classes?
AThey restrict subclassing to the same file
BThey allow unlimited subclassing anywhere
CThey improve safety in when expressions
DThey can be used to represent restricted hierarchies
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.