The Analogy: The Film-Processing Lab
You hand a roll of film across the counter of a processing lab and come back later to collect it. What the counter always gives you is a sealed packet -- never a shout, never a refusal to speak. Sometimes the packet holds your finished prints; sometimes it holds a fault card that reads "film fogged, no prints." Either way you receive exactly one packet, and you have to open it to learn which kind it is. Kotlin's Result<T> is that sealed packet: a single value that carries either a success with your result inside or a failure with the exception inside. The runCatching { } function is the counter itself -- it attempts the risky work and, whatever happens, hands back a packet instead of throwing an exception at you.
There are standard ways to open the packet, and which you choose depends on how much the outcome matters. You can peek and take the prints if they are there or nothing if they are not; you can accept a blank default set when there are no prints; you can hand a failed packet to a specialist who tries to salvage something; or you can insist on the prints and make a scene if the packet turns out to hold a fault card. These are Kotlin's getOrNull, getOrDefault, getOrElse, recover, and getOrThrow, along with the simple checks isSuccess and isFailure and the exceptionOrNull that reads the fault card's reason.
The lab can also do more work on your behalf, but only when the first step succeeded. Ask them to enlarge the prints and the enlargement is applied to real prints when development worked; a fault card passes straight through the enlarger untouched, still a fault card at the far end. This is what map does to a Result: it transforms the value on the success path and leaves a failure exactly as it was. And fold lets you deal with both kinds in one place -- one instruction for prints, another for the fault card -- collapsing the packet down to a single final answer.
The trap is a counter that files absolutely everything as a calm fault card, including the things that were never meant to be filed. If the building's fire alarm goes off mid-development, that is not a "no prints today" outcome -- it is an emergency that must halt the whole operation and reach you immediately. A lab that quietly stuffs the evacuation order into a fault card has hidden a signal that should never have been captured. This is the real hazard of runCatching: it catches every Throwable, including ones you must not swallow -- most sharply a coroutine's CancellationException, which keeps structured cancellation working, and fatal errors like OutOfMemoryError. Turning those into an ordinary failure result breaks the machinery that depends on them propagating.
Syntax or Core Structure
runCatching runs a block and returns a Result<T> -- success carrying the value, failure carrying the exception. You then extract a plain value with one of the getOr... functions.
fun parse(text: String): Result<Int> =
runCatching { text.toInt() }
fun main() {
val good = parse("42")
val bad = parse("oops")
println("good ok? " + good.isSuccess)
println("good value " + good.getOrDefault(-1))
println("bad ok? " + bad.isSuccess)
println("bad value " + bad.getOrDefault(-1))
println("bad has error? " + (bad.exceptionOrNull() != null))
}
Output:
good ok? true
good value 42
bad ok? false
bad value -1
bad has error? true
parse("42") runs "42".toInt() successfully, so good is a success packet: isSuccess is true and getOrDefault(-1) returns the real value 42. parse("oops") throws NumberFormatException inside the block, which runCatching captures into a failure packet: isSuccess is false and getOrDefault(-1) returns the fallback -1. The last line reads the captured exception through exceptionOrNull, which is non-null for a failure, confirming an error was stored without printing its implementation-specific message. The key point is that parse never throws -- it always returns a packet the caller opens on its own terms.
Technical Depth: Opening and Transforming a Result
The Result toolbox
Once you hold a Result<T>, these are the operations that read or transform it. Each treats the success and failure packets differently.
| Operation | On success | On failure |
|---|---|---|
getOrNull() | the value | null |
getOrDefault(d) | the value | d |
getOrElse { } | the value | lambda result (sees the exception) |
getOrThrow() | the value | rethrows the exception |
map { } | transforms the value | unchanged failure |
recover { } | unchanged success | turns failure into a success |
fold(onS, onF) | onS(value) | onF(exception) |
The transforming operations return a new Result, so they chain; the getOr... operations exit the Result world and hand back a plain value.
Recovering from a failure
getOrElse and recover both handle the failure path, but getOrElse yields a plain value while recover yields another Result you can keep chaining.
fun parse(text: String): Result<Int> = runCatching { text.toInt() }
fun main() {
val a = parse("15").getOrElse { 0 }
val b = parse("nope").getOrElse { 0 }
val c = parse("nope").recover { -1 }.getOrThrow()
println("a " + a)
println("b " + b)
println("c " + c)
}
Output:
a 15
b 0
c -1
parse("15").getOrElse { 0 } succeeds, so a is 15 and the lambda never runs. parse("nope").getOrElse { 0 } fails, so the lambda supplies 0 for b. The third line shows recovery: recover { -1 } converts the failure packet into a success packet holding -1, and getOrThrow then safely extracts -1 because the packet is now a success. recover is the tool when you want to stay in the Result pipeline after handling an error.
Transforming with map and collapsing with fold
map transforms only the success value, and fold reduces a Result to a single value by handling both cases at once.
fun parse(text: String): Result<Int> = runCatching { text.toInt() }
fun describe(text: String): String =
parse(text)
.map { it * 2 }
.fold(
onSuccess = { "doubled to " + it },
onFailure = { "could not parse" }
)
fun main() {
println(describe("21"))
println(describe("x"))
}
Output:
doubled to 42
could not parse
For "21", parse succeeds with 21, map { it * 2 } transforms it to 42, and fold takes the onSuccess branch to produce "doubled to 42". For "x", parse fails; map leaves the failure untouched (the doubling never runs), and fold takes the onFailure branch to produce "could not parse". fold is how you exit a Result while giving both outcomes an explicit answer, with no chance of forgetting the failure case.
Side effects with onSuccess and onFailure
onSuccess and onFailure run a side effect for the matching case and return the same Result, so they slot into a chain without changing the value.
fun parse(text: String): Result<Int> = runCatching { text.toInt() }
fun main() {
parse("8")
.onSuccess { println("got " + it) }
.onFailure { println("failed") }
parse("bad")
.onSuccess { println("got " + it) }
.onFailure { println("failed") }
}
Output:
got 8
failed
For "8", the packet is a success, so onSuccess runs and prints "got 8" while onFailure does nothing. For "bad", the packet is a failure, so onSuccess is skipped and onFailure prints "failed". Both functions return the Result unchanged, which is why they can be chained back to back and why they are ideal for logging or metrics without disturbing the value flowing through the pipeline.
map versus mapCatching
map assumes its transform cannot fail and lets any exception from the transform escape; mapCatching runs the transform inside a capture, folding a new failure back into the Result.
fun main() {
val safe = runCatching { "10" }
.mapCatching { it.toInt() * 2 }
val caught = runCatching { "ten" }
.mapCatching { it.toInt() * 2 }
println("safe " + safe.getOrDefault(-1))
println("caught ok? " + caught.isSuccess)
println("caught " + caught.getOrDefault(-1))
}
Output:
safe 20
caught ok? false
caught -1
The first chain starts with the success "10"; mapCatching runs "10".toInt() * 2, which succeeds with 20, so safe.getOrDefault(-1) is 20. The second starts with the success "ten"; mapCatching runs "ten".toInt() * 2, and toInt throws NumberFormatException -- but because it is mapCatching, that exception is captured into a failure packet rather than escaping. So caught.isSuccess is false and getOrDefault(-1) yields -1. Had this been a plain map, the exception would have propagated out of the chain instead of becoming a failure result.
Real World Example: A Retry Helper
A service wants to retry flaky operations, so it builds a helper on top of runCatching: run the block, and while the Result is a failure, try again up to a limit. It looks clean and reusable.
var attempts = 0
fun loadValue(key: String): Int {
attempts += 1
if (key.isEmpty()) throw IllegalArgumentException("empty key") // permanent
return key.length
}
fun retry(times: Int, block: () -> Int): Result<Int> {
var result = runCatching { block() }
var n = 1
while (result.isFailure && n < times) {
result = runCatching { block() } // retries on ANY failure
n += 1
}
return result
}
fun main() {
attempts = 0
val ok = retry(3) { loadValue("abc") }
println("ok = " + ok.getOrNull() + ", attempts = " + attempts)
attempts = 0
val bad = retry(3) { loadValue("") }
println("bad ok? " + bad.isSuccess + ", attempts = " + attempts)
}
Output:
ok = 3, attempts = 1
bad ok? false, attempts = 3
The happy path is efficient. retry runs loadValue("abc") once, gets a success packet holding 3 (the key length), and returns immediately without retrying -- attempts is 1. For a genuinely transient failure that later succeeds, this loop would do exactly what you want.
The empty-key case reveals the flaw. loadValue("") throws IllegalArgumentException, a permanent error that will never succeed no matter how many times it runs. Yet retry keeps going because it only asks result.isFailure, burning all three attempts on an input that was invalid from the start -- attempts reaches 3 before it gives up.
The genuine design flaw is treating every failure as retryable, which follows directly from runCatching flattening all Throwables into one undifferentiated failure packet. The helper cannot tell a transient network blip from a permanent argument error -- or from a real bug, or from a coroutine's CancellationException that should abort the whole operation rather than be retried. It is the analogy's fire alarm filed as a routine fault card. The fix is to inspect what actually failed before retrying: read result.exceptionOrNull() and continue only for exception types known to be transient, while rethrowing or immediately returning for permanent errors and never retrying a CancellationException. The broader limitation is that Result deliberately erases the distinction between exception types at the API surface, so any logic that must branch on the kind of failure has to reach back into exceptionOrNull and check -- runCatching is a capture tool, not a classification tool.
Common Mistakes
- Using
runCatchinginside a coroutine without excludingCancellationException. It catches allThrowable, so it swallows the cancellation signal and breaks structured concurrency. RethrowCancellationExceptionor use a narrower try/catch.
- Treating every
Resultfailure as retryable.runCatchingerases the exception type at the surface, so retry logic that only checksisFailureretries permanent errors and bugs. InspectexceptionOrNullfirst.
- Ignoring a
Resultyou produced. AResultreturned and never inspected silently drops the failure. Always consume it withfold,getOrElse,onFailure, or a check.
- Reaching for
Resultas a general return type across module boundaries.Resultwas designed for scoped, internal use; exposing it widely is discouraged. Prefer a sealed class or nullable for public APIs.
- Calling
getOrThrowand defeating the purpose. If you immediatelygetOrThrow, you have converted a captured failure straight back into a thrown exception; you might as well not have wrapped it.
- Confusing
mapandmapCatching.mapassumes its transform cannot fail; if the transform itself throws, usemapCatchingso the new exception is captured into theResultrather than escaping.
- Swallowing the exception with
getOrNullwhen you needed the reason.getOrNulldiscards why it failed. UsegetOrElse { e -> ... }orexceptionOrNullwhen the failure detail matters.
- Wrapping pure control flow in
runCatching. For expected, non-exceptional outcomes prefer...OrNullfunctions or a sealed result; reserverunCatchingfor genuinely exception-throwing operations.
- Assuming a failed
Resultshort-circuits later side effects. Only theResult-aware operations skip on failure; ordinary code aftergetOrDefaultruns regardless. Keep failure handling inside theResultchain.
Best Practices
- Use
runCatchingto turn a throwing operation into a value you can pass around, then handle both outcomes explicitly withfold. - In coroutines, avoid a bare
runCatchingaround suspending calls, or rethrowCancellationExceptionso cancellation still propagates. - Retry only on exception types known to be transient, inspecting
exceptionOrNullrather than treating every failure alike. - Keep
Resultfor internal, scoped error handling; expose sealed classes or nullables at public API boundaries. - Prefer
getOrElseandrecoverovergetOrThrowwhen you have a sensible fallback, so failures do not become thrown exceptions again. - Use
mapCatchingwhen a transform can itself fail, keeping the new exception inside theResult. - Chain
map,recover, andfoldto build a clear success-or-failure pipeline instead of nesting try/catch blocks. - Never leave a
Resultuninspected; an unconsumed failure is a silently dropped error.
Practice Exercises
- Write a
fun safeParse(s: String): Result<Int>usingrunCatching, and print the outcome of a valid and an invalid input usingfoldwith distinct success and failure messages.
- Chain
mapandgetOrElseon a parsedResultto double the value on success and yield a default on failure, confirming both paths.
- Reproduce the retry flaw: build a retry loop that continues on any
isFailure, show it burns all attempts on a permanentIllegalArgumentException, then fix it to inspectexceptionOrNulland stop retrying permanent errors.
- Use
recoverto convert a failedResult<Int>into a success holding a sentinel value, thengetOrThrowit and confirm no exception is thrown.