Kotlin 2 · Classes and types

Sealed types for fixed alternatives

A sealed interface limits its implementations, so when must handle every case.

sealed interface Result {
    data class Success(val value: Int) : Result
    data class Failure(val message: String) : Result
}

fun show(r: Result) = when (r) {
    is Result.Success -> "ok ${r.value}"
    is Result.Failure -> "error ${r.message}"
}

Official Kotlin 2 documentation

More classes and types commands

All classes and types commands · Kotlin 2 cheatsheet

Was this page helpful?