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
sealed interface TrailEventfixes the set of implementations at compile time.- Cases are data classes or singletons —
object Sunsetcarries no fields. - The
whenneeds noelse: cover every case or the file will not compile.
Keywords and builtins used here
DoubleSightingStringSunsetTrailEventWashoutclassdatadescribefuninterfaceismainobjectsealedvalwhen
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.
Step 2 of 3 in Classes & objects, step 14 of 27 in Language basics.