Kotlin

Sealed Classes — Closed Type Hierarchies

admin by @admin ADMIN
Jun 16, 2026
Jun 1, 2026
Public
0 0 up · 0 down Sign in to vote
`sealed` restricts subclassing to the same module. Combined with exhaustive `when`, the compiler enforces handling of every variant — refactor-friendly state machines.
Kotlin
Raw
sealed class Result<out T> {
    data class Ok<T>(val value: T) : Result<T>()
    data class Err(val message: String) : Result<Nothing>()
    object Loading : Result<Nothing>()
}

fun describe(r: Result<Int>): String = when (r) {
    is Result.Ok      -> "got ${r.value}"           // r.value smart-cast to Int
    is Result.Err     -> "failed: ${r.message}"
    Result.Loading    -> "still loading…"
    // No `else` needed — the compiler verifies every variant is handled.
    // Add a new variant later → every `when` over Result will refuse to compile.
}

fun main() {
    println(describe(Result.Ok(42)))
    println(describe(Result.Err("network down")))
    println(describe(Result.Loading))
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.