0
0
Kotlinprogramming~5 mins

Sealed classes for restricted hierarchies in 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 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?
AThey restrict subclassing to the same package.
BThey allow subclassing from any file.
CThey cannot have subclasses.
DThey are the same as abstract classes.
Why does Kotlin allow omitting the else branch in a when expression with sealed classes?
ABecause sealed classes have no subclasses.
BBecause <code>else</code> is never needed in Kotlin.
CBecause sealed classes are final.
DBecause the compiler knows all subclasses at compile time.
Which of these is NOT true about sealed classes?
AThey can have abstract members.
BThey can be instantiated directly.
CTheir subclasses must be in the same file.
DThey help with exhaustive <code>when</code> checks.
What keyword is used to declare a sealed class in Kotlin?
Asealed
Bopen
Cabstract
Dfinal
Which of the following is a benefit of using sealed classes?
AUnlimited subclassing across packages.
BBetter control over class hierarchies and safer code.
CThey automatically generate getters and setters.
DThey allow multiple inheritance.
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.