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))
}
Create a free account and build your private vault. Share publicly whenever you want.