The Analogy: The Loan Underwriting Desk
At a loan underwriting desk, every application comes back with exactly one decision slip, and the slips are pre-printed from a fixed set. There is an APPROVED slip that carries the approved amount, a DECLINED slip that carries a reason code, and a REFERRED slip that carries a list of missing documents. The printer holds these three designs and no others -- there is no such thing as a vague "something is wrong" slip. A Kotlin sealed error type works the same way: a closed, known set of outcome variants, so a function returns one of a fixed roster of possibilities rather than either a value or a thrown surprise.
Each slip carries its own specific paperwork. The APPROVED slip has an amount and nothing about reasons; the DECLINED slip has a reason and no amount; the REFERRED slip lists the documents still needed. This is what makes a sealed outcome richer than a bare success-or-failure flag: every variant is a small data record shaped for its own case, so the handler reads structured facts instead of guessing. The outcome is a value you hold in your hand, passed back directly from the desk.
The clerk who acts on a decision works from a checklist, and the case-management system refuses to let them close the file until the checklist has an action for every slip type the printer can produce. Because the set of slips is closed, "every type" is a finite, checkable list. This is the exhaustive when: when you branch on a sealed type, the Kotlin compiler verifies that you have covered every variant, and it will not compile if you have missed one -- the filing system enforcing that no possible outcome is left unhandled.
Contrast this with the older way of working: an underwriter who, upon hitting a problem, pulls a fire alarm that echoes up through the building until some manager happens to hear it and deals with it. That is an exception -- it interrupts, it travels up the call chain, and it can be missed entirely if no one along the way is listening for it. The failure comes from confusing the two mechanisms. Treating an ordinary, expected decline as a pulled alarm is over-dramatic and easy to drop on the floor; it should be a routine slip handed back. The opposite over-use is modeling genuinely exceptional, unforeseeable faults -- the building actually on fire, a database that vanished -- as decision slips, which forces every caller to handle "impossible" variants and clutters every checklist. The craft is to return expected, enumerable outcomes as sealed slips and reserve exceptions for the truly exceptional.
Syntax or Core Structure
A sealed interface (or class) defines a closed family of outcomes, each variant carrying its own data. A when over the sealed type is checked for exhaustiveness with no else.
sealed interface LoanDecision {
data class Approved(val amount: Int) : LoanDecision
data class Declined(val reason: String) : LoanDecision
data object Referred : LoanDecision
}
fun decide(score: Int): LoanDecision = when {
score >= 700 -> LoanDecision.Approved(5000)
score >= 500 -> LoanDecision.Referred
else -> LoanDecision.Declined("score too low")
}
fun explain(d: LoanDecision): String = when (d) {
is LoanDecision.Approved -> "approved for " + d.amount
is LoanDecision.Declined -> "declined: " + d.reason
LoanDecision.Referred -> "referred for review"
}
fun main() {
println(explain(decide(720)))
println(explain(decide(600)))
println(explain(decide(400)))
}
Output:
approved for 5000
referred for review
declined: score too low
LoanDecision is a sealed interface with three variants: Approved carrying an amount, Declined carrying a reason, and the stateless Referred as a data object. decide returns one of them as an ordinary value -- no exception is thrown. The explain function branches with a when that has no else; it compiles precisely because the three is/value branches cover every variant of the sealed type. The three calls exercise each path: 720 approves for 5000, 600 refers, 400 declines with its reason. The error is a value in the return type, impossible for a caller to ignore.
Technical Depth: Sealed Outcomes versus Exceptions
When to reach for each
Both mechanisms report failure, but they make different trade-offs. The table lays them side by side.
| Aspect | Sealed error type | Exception |
|---|---|---|
| Appears in the signature | yes, in the return type | no (unchecked) |
| Can a caller forget it? | no -- when is exhaustive | yes -- silent propagation |
| Cost | a returned object | stack unwinding |
| Best for | expected, enumerable outcomes | truly exceptional faults |
| Carries data per case | yes, per variant | yes, per exception |
| Composes with | map, when, fold | try/catch |
Use a sealed error type when the failures are a known, small set that callers routinely handle. Keep exceptions for the unforeseeable and unrecoverable.
A generic Ok/Err outcome
A reusable sealed Outcome type lets you transform the success case while passing failures through untouched, in the style of railway-oriented programming.
sealed interface Outcome<out T> {
data class Ok<T>(val value: T) : Outcome<T>
data class Err(val message: String) : Outcome<Nothing>
}
fun <T, R> Outcome<T>.map(f: (T) -> R): Outcome<R> = when (this) {
is Outcome.Ok -> Outcome.Ok(f(value))
is Outcome.Err -> this
}
fun parse(s: String): Outcome<Int> {
val n = s.toIntOrNull()
return if (n != null) Outcome.Ok(n) else Outcome.Err("bad number: " + s)
}
fun render(o: Outcome<Int>): String = when (o) {
is Outcome.Ok -> "value " + o.value
is Outcome.Err -> "error " + o.message
}
fun main() {
println(render(parse("21").map { it * 2 }))
println(render(parse("no").map { it * 2 }))
}
Output:
value 42
error bad number: no
Outcome has two variants, Ok carrying a value and Err carrying a message; note Err implements Outcome<Nothing>, so a single Err fits any Outcome<T> thanks to the out variance and Nothing being a subtype of every type. The map extension transforms the value inside an Ok and returns an Err unchanged. For "21", parse gives Ok(21), map doubles it to Ok(42), and render prints "value 42". For "no", parse gives Err("bad number: no"), map passes it straight through, and render prints "error bad number: no". The failure flows down the pipeline as a value, never as a thrown control transfer.
Exhaustiveness protects you when the set grows
Because the compiler checks a when over a sealed type for completeness, adding a variant turns every non-exhaustive handler into a compile error rather than a silent gap.
sealed interface Status {
data object Active : Status
data object Paused : Status
data object Closed : Status
}
fun label(s: Status): String = when (s) {
Status.Active -> "active"
Status.Paused -> "paused"
Status.Closed -> "closed"
}
fun main() {
println(label(Status.Active))
println(label(Status.Paused))
println(label(Status.Closed))
}
Output:
active
paused
closed
The when covers all three Status values with no else, so it compiles and each call prints its label. The real benefit is future-proofing: if a fourth status were added to the sealed interface, this when would immediately fail to compile, pointing you at exactly the handler that needs a new branch. An else would have hidden that gap by silently absorbing the new case, which is why exhaustive when without else is the safer pattern for sealed types.
Extracting a plain value with an extension
When a caller genuinely wants to leave the sealed world with a fallback, an extension function makes the exit explicit and still exhaustive.
sealed interface Parsed {
data class Ok(val n: Int) : Parsed
data class Fail(val why: String) : Parsed
}
fun parse(s: String): Parsed {
val n = s.toIntOrNull()
return if (n != null) Parsed.Ok(n) else Parsed.Fail("not a number")
}
fun Parsed.orDefault(d: Int): Int = when (this) {
is Parsed.Ok -> n
is Parsed.Fail -> d
}
fun main() {
println(parse("30").orDefault(-1))
println(parse("x").orDefault(-1))
}
Output:
30
-1
The orDefault extension is an exhaustive when that returns the value from an Ok and the supplied default from a Fail. parse("30") gives Ok(30), so orDefault(-1) returns 30; parse("x") gives Fail, so orDefault(-1) returns -1. Crucially the collapse to a plain Int happens in one clearly-named place with every case handled, rather than being scattered as ad-hoc is checks -- so if a third variant is added, only this one function needs updating and the compiler will insist on it.
Real World Example: A Payment Result Collapsed Too Early
A checkout flow calls a payment gateway that can return three outcomes, modelled as a sealed PaymentResult: a success with a transaction id, a decline with a reason, or a "requires action" case carrying a verification URL the customer must visit. A helper isPaid reduces the result to a boolean so the calling code can stay simple.
sealed interface PaymentResult {
data class Success(val txnId: String) : PaymentResult
data class Declined(val reason: String) : PaymentResult
data class RequiresAction(val url: String) : PaymentResult
}
fun charge(scenario: String): PaymentResult = when (scenario) {
"ok" -> PaymentResult.Success("txn-1")
"declined" -> PaymentResult.Declined("card expired")
else -> PaymentResult.RequiresAction("verify-url")
}
fun isPaid(r: PaymentResult): Boolean = r is PaymentResult.Success // collapses 3 -> 2
fun userMessage(scenario: String): String =
if (isPaid(charge(scenario))) "payment complete" else "payment failed"
fun main() {
println(userMessage("ok"))
println(userMessage("declined"))
println(userMessage("action"))
}
Output:
payment complete
payment failed
payment failed
Two of the three cases look fine. A successful charge yields "payment complete", and a genuine decline yields "payment failed" -- reasonable messages that would pass a quick review. The sealed type is doing its job at the gateway boundary, returning a precise, data-carrying outcome.
The third line is the bug. The "action" scenario returns RequiresAction, which means the payment can still succeed if the customer completes a verification step at the given URL -- but userMessage reports "payment failed", identical to a hard decline. A customer who only needed to tap a confirmation is told their payment failed, and the checkout abandons a sale that would have gone through.
The genuine design flaw is collapsing a rich three-way sealed outcome into a boolean with isPaid, which erases the distinction the sealed type existed to preserve. It is the analogy's mistake of reducing three distinct decision slips to a single yes/no rubber stamp, throwing away the "referred, here is what is needed" instructions. Once the outcome is a Boolean, RequiresAction and Declined are indistinguishable, and no downstream code can recover the difference. The fix is to handle the sealed type with an exhaustive when at the point where the decision actually matters -- when (charge(scenario)) { is Success -> ...; is Declined -> ...; is RequiresAction -> redirectTo(it.url) } -- giving the actionable case its own branch. The broader limitation is that a sealed type's safety lasts only until someone flattens it into a poorer type; every premature conversion to Boolean or a nullable discards cases the compiler would otherwise have forced you to consider.
Common Mistakes
- Collapsing a rich sealed outcome into a boolean or nullable too early. Reducing a three-way result to
isPaid: Booleanerases cases the type existed to preserve. Handle the sealed type where the distinction matters.
- Adding an
elseto awhenover a sealed type. Theelsesilently absorbs future variants, defeating exhaustiveness. Omit it so the compiler flags any new case.
- Using sealed errors for genuinely exceptional faults. Modelling "database vanished" or "out of memory" as a variant forces every caller to handle the unforeseeable. Reserve sealed outcomes for expected failures.
- Throwing from inside a sealed-outcome pipeline. Mixing a thrown exception into code that returns outcomes reintroduces the silent-propagation problem you adopted sealed types to avoid. Return an error variant instead.
- Forgetting variance on a generic outcome. Without
out, anOutcome<Nothing>error will not fit anOutcome<String>. Declare the value parameteroutso a sharedErrworks across types.
- Making the error variant carry too little. A bare
Failurewith no fields is barely better than a boolean. Give each error variant the data a handler needs to act.
- Nesting outcomes without flattening. An
Outcome<Outcome<T>>from chaining is awkward; provide aflatMap-style operator that unwraps one level so pipelines stay flat.
- Defining variants in scattered files for a non-local hierarchy. Sealed subtypes must be in the same module (and, historically, package or file). Keep the family together so the compiler can enforce exhaustiveness.
- Overusing sealed results for trivial cases. When the only outcomes are "value" or "absent", a nullable is simpler than a two-variant sealed type. Escalate to sealed types when there are several meaningful cases carrying data.
Best Practices
- Model expected, enumerable failures as a sealed error type so they appear in the signature and cannot be silently ignored.
- Branch on sealed types with an exhaustive
whenand noelse, letting the compiler force coverage of every variant. - Give each error variant the fields a handler needs, so the outcome carries actionable data rather than a bare flag.
- Keep the rich sealed type intact through the pipeline; avoid collapsing to
Booleanor a nullable until you truly no longer need the distinctions. - Declare a generic outcome's value parameter
outand let the error variant implementOutcome<Nothing>so one error fits every result type. - Reserve exceptions for the genuinely exceptional and unrecoverable, and sealed outcomes for the failures callers routinely handle.
- Provide
mapandflatMapoperators on your outcome type to compose success paths while passing failures through unchanged. - Prefer a nullable for simple present-or-absent cases, escalating to a sealed type only when several data-bearing outcomes exist.
Practice Exercises
- Define a sealed
interface FetchResultwithOk(data),NotFound, andServerError(code), write a function returning one, and handle it with an exhaustivewhenthat the compiler forces to cover every case.
- Add a generic
Outcome<out T>withOkandErr, implement amapthat transformsOkand passesErrthrough, and confirm both paths with a parse-and-double pipeline.
- Reproduce the collapse flaw: reduce a three-variant payment result to a boolean, show that the actionable case is misreported as failure, then fix it with an exhaustive
whenthat handles the actionable case distinctly.
- Take a sealed
Statuswith three values and an exhaustivewhen, add a fourth value, and observe that thewhenno longer compiles until you handle it -- demonstrating why omittingelseis safer.