Exhaustive when with Sealed Hierarchies
Write complete when expressions that cover every sealed variant.
Exhaustive when
A when expression used as an expression must be exhaustive — every possible value handled. Sealed hierarchies let the compiler verify this for you.
Non-Exhaustive when on Open Type
For ordinary classes, the compiler can't check all subtypes — it requires an else branch.
open class Shape
class Circle : Shape()
class Square : Shape()
fun describe(s: Shape) = when (s) {
is Circle -> "circle"
is Square -> "square"
else -> "unknown" // required
}
fun main() { println(describe(Circle())) }All lessons in this course
- sealed class vs sealed interface: When to Use Each
- Exhaustive when with Sealed Hierarchies
- Modeling UI State with Sealed Classes
- Nesting and Combining Sealed Hierarchies