0Pricing
Kotlin Academy · Lesson

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

  1. sealed class vs sealed interface: When to Use Each
  2. Exhaustive when with Sealed Hierarchies
  3. Modeling UI State with Sealed Classes
  4. Nesting and Combining Sealed Hierarchies
← Back to Kotlin Academy