KtKotlin
AdvancedLesson 13 of 16

Sealed Classes, Value Classes & Exhaustive when – Kotlin

Modeling closed hierarchies and type-safe wrappers with no overhead.

A sealed type has a fixed set of subtypes known to the compiler (in the same package and module). A when over it without else is checked by the compiler for completeness. data object (Kotlin 1.9) is a singleton with a sensible toString.

sealed interface Form
data class Kreis(val radius: Double) : Form
data class Rechteck(val breite: Double, val hoehe: Double) : Form
data object Punkt : Form

fun flaeche(f: Form): Double = when (f) {
    is Kreis -> Math.PI * f.radius * f.radius     // smart cast to Kreis
    is Rechteck -> f.breite * f.hoehe
    Punkt -> 0.0
}   // If you add a new shape, the compiler reports the missing case

println(flaeche(Rechteck(3.0, 4.0)))    // 12.0
println(Punkt)                          // Punkt

Sealed types are perfect for results and states: instead of exceptions for expected errors, you model success and failure as types.

sealed interface Ergebnis<out T> {
    data class Erfolg<T>(val wert: T) : Ergebnis<T>
    data class Fehler(val meldung: String) : Ergebnis<Nothing>
}

fun teile(a: Int, b: Int): Ergebnis<Int> =
    if (b == 0) Ergebnis.Fehler("Division by zero") else Ergebnis.Erfolg(a / b)

for (b in listOf(2, 0)) {
    val text = when (val e = teile(10, b)) {
        is Ergebnis.Erfolg -> "Result: ${e.wert}"
        is Ergebnis.Fehler -> "Error: ${e.meldung}"
    }
    println(text)        // Result: 5  /  Error: Division by zero
}

A value class wraps a single value in its own type – at runtime usually without an additional object. This way you never mix up a UserId with a ProduktId:

@JvmInline
value class UserId(val wert: Long)

@JvmInline
value class Email(val adresse: String) {
    init { require("@" in adresse) { "Invalid email" } }
}

fun lade(id: UserId) = "User ${id.wert}"
println(lade(UserId(7)))     // User 7
// lade(7L)                  // Error: Long is not a UserId
TipWith generics using out T (covariance), Ergebnis<Nothing> can appear anywhere Ergebnis<Int> is expected – that is why Fehler fits into every Ergebnis variant.
WarningAll direct subtypes of a sealed type must be in the same package and module. External libraries therefore cannot extend your hierarchy.