Sealed Result Hierarchies
Custom result types.
Beyond the Built-in Result
Kotlin's Result only carries an exception on failure. Often you want richer, typed error information. A sealed class hierarchy lets you model exactly the outcomes your domain has.
A Sealed Outcome
Define a sealed type with success and error subclasses. The compiler knows all cases, enabling exhaustive handling.
sealed class Outcome<out T> {
data class Ok<T>(val value: T) : Outcome<T>()
data class Err(val message: String) : Outcome<Nothing>()
}
fun main() {
val r: Outcome<Int> = Outcome.Ok(5)
println(r)
}All lessons in this course
- The Result Type
- runCatching
- Sealed Result Hierarchies
- Functional Error Handling