0
0
Kotlinprogramming~10 mins

Sealed classes with when exhaustive check in Kotlin - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Sealed classes with when exhaustive check
Define sealed class
Create subclasses
Use when expression
Check all subclasses covered?
NoCompile error
Yes
Code compiles and runs safely
Sealed classes restrict subclassing to known types. The when expression must cover all subclasses, ensuring safe exhaustive checks.
Execution Sample
Kotlin
sealed class Shape {
    data class Circle(val radius: Double) : Shape()
    data class Rectangle(val width: Double, val height: Double) : Shape()
}

fun area(shape: Shape) = when(shape) {
    is Shape.Circle -> Math.PI * shape.radius * shape.radius
    is Shape.Rectangle -> shape.width * shape.height
}
Calculates area for all Shape subclasses using when with exhaustive check.
Execution Table
StepActionInputConditionBranch TakenOutput
1Call area with Circle(2.0)Circle(radius=2.0)shape is Circle?YesArea = π * 2.0 * 2.0 = 12.566370614359172
2Call area with Rectangle(3.0,4.0)Rectangle(width=3.0,height=4.0)shape is Circle?NoCheck next branch
3Check shape is Rectangle?Rectangle(width=3.0,height=4.0)shape is Rectangle?YesArea = 3.0 * 4.0 = 12.0
4All subclasses covered?Circle and RectangleYesNo else neededFunction returns correct area
5Call area with unknown subclassNot possibleN/AN/ACompile error if missing branch
💡 Execution stops after matching the correct subclass; all subclasses must be covered for compilation.
Variable Tracker
VariableStartAfter 1After 2After 3Final
shapeN/ACircle(radius=2.0)Rectangle(width=3.0,height=4.0)N/AN/A
OutputN/A12.566370614359172N/A12.0N/A
Key Moments - 2 Insights
Why does the compiler force me to cover all subclasses in the when expression?
Because the sealed class restricts subclasses, the compiler knows all possible types. If you miss one, it warns or errors to prevent runtime mistakes. See execution_table row 5.
What happens if I add a new subclass to the sealed class but forget to update the when expression?
The compiler will show an error for non-exhaustive when, forcing you to handle the new subclass. This keeps your code safe and up-to-date.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the output when area is called with Circle(radius=2.0)?
A12.0
B12.566370614359172
CError
D0
💡 Hint
Check execution_table row 1 for output when shape is Circle.
At which step does the when expression check if the shape is a Rectangle?
AStep 1
BStep 2
CStep 3
DStep 4
💡 Hint
Look at execution_table rows 2 and 3 for the branch checks.
If a new subclass Triangle is added but not handled in when, what happens?
ACompile error for non-exhaustive when
BRuntime exception thrown
CCode compiles but returns null
DTriangle is ignored silently
💡 Hint
See key_moments about compiler forcing exhaustive when checks.
Concept Snapshot
sealed class Shape {
  data class Circle(val r: Double) : Shape()
  data class Rectangle(val w: Double, val h: Double) : Shape()
}

fun area(s: Shape) = when(s) {
  is Shape.Circle -> Math.PI * s.r * s.r
  is Shape.Rectangle -> s.w * s.h
} // must cover all subclasses, else compile error
Full Transcript
Sealed classes in Kotlin let you define a fixed set of subclasses. When you use a when expression on a sealed class, Kotlin requires you to cover all subclasses. This makes your code safe because you handle every possible case. For example, if Shape is sealed with Circle and Rectangle subclasses, your when must handle both. If you miss one, the compiler shows an error. This exhaustive check prevents bugs. The execution table shows how the when expression checks the type step-by-step and returns the correct area. If you add a new subclass later, you must update the when expression or the compiler will warn you. This helps keep your code correct and easy to maintain.