typestar

Sealed hierarchies in Kotlin

A closed set of cases the compiler can check exhaustively.

// A sealed hierarchy is closed: when over it needs no else branch.
sealed interface TrailEvent
data class Sighting(val species: String) : TrailEvent
data class Washout(val atKm: Double) : TrailEvent
object Sunset : TrailEvent

fun describe(event: TrailEvent): String = when (event) {
    is Sighting -> "Saw a ${event.species}"
    is Washout -> "Turn back at km ${event.atKm}"
    Sunset -> "Headlamps on"
}

fun main() {
    println(describe(Sighting("marmot")))
    println(describe(Washout(11.5)))
    println(describe(Sunset))
}

How it works

  1. sealed interface TrailEvent fixes the set of implementations at compile time.
  2. Cases are data classes or singletons — object Sunset carries no fields.
  3. The when needs no else: cover every case or the file will not compile.

Keywords and builtins used here

The run, in numbers

Lines
17
Characters to type
510
Tokens
112
Three-star pace
65 tpm

At the three-star pace of 65 tokens a minute, this run takes about 103 seconds.

Type this snippet

Step 2 of 3 in Classes & objects, step 14 of 27 in Language basics.

← Previous Next →