Skip to content
Tutorials Center
My learning

Topics

Lesson 78 of 134 ยท Error Handling and Resources

The Result Type

Learn Kotlin's Result type - runCatching, getOrNull, getOrElse, map, mapCatching, recover, fold, returning Result from functions, and when a sealed class or plain exceptions are better.

An exception is an invisible second return value. A function declared as fun load(): Config can also "return" an IOException, a NumberFormatException or anything else, and nothing in its signature says so. Kotlin has no checked exceptions (see Exceptions), so callers must remember which failures matter. The standard library's Result<T> type is one way to make a failure an ordinary value that you can store, pass around, transform and inspect.

A Result<T> is always in one of two states: success, holding a value of type T, or failure, holding a Throwable. You rarely create one by hand; the usual entry point is runCatching { ... }, which runs a block and captures whatever happens. This lesson covers the whole API, shows how to design functions that return Result, and, just as important, explains when you should use something else.

Creating a Result

runCatching returns Result<T> where T is the type of the block's last expression. If the block throws, the exception is captured instead of propagating.

Kotlin runCatching, success and failure

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The text form is Success(42) for a success and Failure(java.lang.NumberFormatException: ...) for a failure, which is handy while debugging. Result.success(value) and Result.failure(exception) build results directly, for example in a fake used by a test.

There is also a variant that runs on a receiver: value.runCatching { ... }, where this is the value. For most code the plain block is clearer.

Getting the value out

A result is a box. The functions below open it, and each one answers the question "what if it failed?" differently:

Function On success On failure
getOrNull() the value null
getOrDefault(d) the value d
getOrElse { e -> ... } the value the lambda's result (receives the exception)
getOrThrow() the value rethrows the exception
exceptionOrNull() null the exception
fold(onSuccess, onFailure) onSuccess(value) onFailure(exception)
Kotlin Opening a Result

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

getOrElse is the workhorse for "use a fallback", and unlike getOrDefault its fallback is computed only when needed. fold is the best choice when both outcomes must produce the same kind of value, such as a message for the user.

Transforming results

Most of the time you do not open the box immediately; you build a pipeline. These functions transform a result while keeping the success/failure state in the type.

  • map { } transforms the success value. An exception thrown inside the lambda is not caught, it escapes.
  • mapCatching { } is map that also captures an exception thrown inside the lambda.
  • recover { e -> value } turns a failure into a success value; recoverCatching does the same while capturing exceptions thrown by the recovery.
  • onSuccess { } and onFailure { } run a side effect (logging, for instance) and return the original result so the chain continues.
Kotlin A Result pipeline

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

For "0" the parse succeeds, then reciprocalPercent(0) throws ArithmeticException inside mapCatching; the pipeline captures it, and recover replaces it with -1. If you wrote map instead of mapCatching, that exception would have crashed the program. This is the single most common Result mistake, so remember: map does not catch, mapCatching does.

Note also that recover { -1 } here handles every failure the same way. In real code you often want to recover from only some exception types. Inspect the exception inside the lambda and rethrow what you cannot handle:

Kotlin
// read-only example: recovering selectively
val value = runCatching { loadFromCache() }
    .recoverCatching { e ->
        if (e is java.io.FileNotFoundException) loadFromNetwork() else throw e
    }
    .getOrThrow()

Returning Result from your own functions

Result<T> can be a return type, a parameter and a property type. A function that returns it announces "this can fail, and I give you the failure as a value":

Kotlin A function that returns Result

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Since Kotlin 1.5 you may use Result as a return type without any compiler flag. Two things are worth knowing about its design. First, it is a value class, so the success case usually carries no extra object. Second, it has no type parameter for the error: the failure is always a Throwable. That is deliberate (it mirrors exceptions), but it also means a caller cannot tell from the type what can go wrong.

Where Result shines, and where it does not

Result is a good fit when:

  • you need to capture an exception and carry it elsewhere: across threads, into a collection, into a callback, or into a test double. This is exactly why the coroutines library uses it for Continuation.
  • a chain of fallible steps ends in a single decision (getOrElse, fold).
  • you want "try this, else that" in one expression.

It is a poor fit when:

  • The caller must handle specific, known failures. Result<User> says nothing about "not found" versus "database down". A sealed type documents all outcomes and lets when check you handled each of them (see Sealed Classes and Interfaces):
Kotlin
// read-only example: a result type with domain errors
sealed interface LookupResult {
    data class Found(val user: User) : LookupResult
    data object NotFound : LookupResult
    data class Unavailable(val reason: String) : LookupResult
}
  • The failure is a programmer error. A negative age passed to a constructor is a bug; throw IllegalArgumentException with require instead of wrapping it.
  • The failure is simply "no value". Return T? and use ?:; there is no need for an exception object at all.
  • It is a public library API. Many teams avoid Result in public signatures: it can't be used from Java as nicely (the compiled signature is mangled), and the unspecific error type makes the API harder to evolve.

runCatching catches Throwable, including Error subclasses such as OutOfMemoryError, and in coroutines it catches CancellationException. Swallowing that exception stops cancellation from working, so inside a suspend function either rethrow it (if (e is CancellationException) throw e) or use an ordinary try/catch for the specific exceptions you expect. See Cancellation and Timeouts.

A few pitfalls

Ignoring the result. A function returning Result that you call and never inspect has silently swallowed its failure:

Kotlin A swallowed failure

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The second call prints nothing and the program goes on. Always do something with a failure: onFailure { log(it) }, getOrThrow(), or return the result to your caller.

Result of Result. If a function already returns Result<T>, runCatching { thatFunction() } gives Result<Result<T>>. Use the result directly, or getOrThrow() inside the block.

Hiding the cause. When you convert a failure into a default (getOrDefault(0)), the information about why it failed is gone. For a value that matters, log the exception first with onFailure.

Success holds null. Result<String?> can succeed with null; getOrNull() then returns null for both a null success and a failure. Use isSuccess or fold when the difference matters.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does runCatching { 10 / 0 } return?

    runCatching captures any Throwable thrown by the block and returns it inside a Result, so the call itself never throws.
  2. 2. An exception is thrown inside the lambda of result.map { ... }. What happens?

    map does not catch exceptions thrown by its lambda; use mapCatching if the transformation can fail.
  3. 3. Which function returns a fallback computed from the exception only when the result is a failure?

    getOrElse takes a lambda that receives the exception and runs only on failure. getOrDefault takes a ready-made value.
  4. 4. When is a sealed class usually a better choice than Result?

    Result carries only a Throwable, so it cannot tell callers which domain failures exist. A sealed hierarchy lists them and the compiler checks that a when handles all of them.
  5. 5. Why is runCatching risky inside suspend functions?

    Cancellation is signalled with CancellationException. If runCatching swallows it, the coroutine keeps running after it was cancelled.

Summary

  • Result<T> holds either a success value or a Throwable; runCatching { } creates one from any block, and Result.success / Result.failure build one directly.
  • Open it with getOrNull, getOrDefault, getOrElse, getOrThrow, exceptionOrNull or fold.
  • Transform it with map (does not catch), mapCatching (catches), recover, recoverCatching; observe it with onSuccess and onFailure.
  • Functions may return Result<T>, but never ignore a returned result: that swallows the failure.
  • Prefer a sealed type when callers must tell failure kinds apart, T? for "no value", and require/check for programmer errors.
  • runCatching catches CancellationException; handle it explicitly in coroutine code.

Next: require, check and assert