Kotlin Academy · Lesson

runCatching and Result<T>

Use runCatching to wrap exceptions in Result and process them functionally.

Lesson 3 of 413 steps

runCatching and Result<T> is a free Kotlin Academy lesson on CoddyKit. This is lesson 3 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the Kotlin Academy learning path, and your progress syncs across the web and the CoddyKit app. The Kotlin Academy course includes 4 lessons in total.

Result<T> in a Nutshell

Result<T> is Kotlin's wrapper for an operation outcome: either a success with a value of type T or a failure with a Throwable.

runCatching Basics

runCatching { ... } runs the block and wraps the outcome in a Result.

fun main() {
    val good = runCatching { 10 / 2 }
    val bad  = runCatching { 10 / 0 }
    println("good isSuccess = ${good.isSuccess}")
    println("bad isFailure  = ${bad.isFailure}")
}

Extracting the Value

getOrNull returns the value or null. getOrThrow rethrows on failure. getOrDefault returns a fallback.

fun main() {
    val r = runCatching { "42".toInt() }
    println(r.getOrNull())          // 42
    println(r.getOrDefault(-1))    // 42
    val bad = runCatching { "x".toInt() }
    println(bad.getOrNull())       // null
    println(bad.getOrDefault(0))   // 0
}

Extracting the Exception

exceptionOrNull() returns the exception on failure, or null on success.

fun main() {
    val r = runCatching { error("boom") }
    println(r.exceptionOrNull()?.message) // boom
}

Transforming with map

map { value -> ... } transforms the success value. Failure passes through untouched.

fun main() {
    val r = runCatching { "10" }.map { it.toInt() * 2 }
    println(r.getOrNull()) // 20
}

mapCatching

mapCatching wraps the transformation in a try/catch so exceptions inside the lambda also become failures.

fun main() {
    val r = runCatching { "abc" }.mapCatching { it.toInt() }
    println(r.isFailure) // true
    println(r.exceptionOrNull()?.message) // For input string: "abc"
}

recover and recoverCatching

recover { e -> fallback } turns failures into successes by computing a recovery value.

fun main() {
    val r = runCatching { "abc".toInt() }
        .recover { -1 }
    println(r.getOrNull()) // -1
}

onSuccess / onFailure

Use onSuccess and onFailure for side effects without changing the Result.

fun main() {
    runCatching { "42".toInt() }
        .onSuccess { println("parsed: $it") }
        .onFailure { println("failed: ${it.message}") }
}

fold for Both Paths

fold(onSuccess, onFailure) returns a unified type from either branch — useful for converting to a UI-ready value.

fun main() {
    val r = runCatching { "10".toInt() }
    val msg: String = r.fold(
        onSuccess = { "OK: $it" },
        onFailure = { "ERR: ${it.message}" }
    )
    println(msg)
}

Using Result as Return Type

Functions can return Result<T> to make error handling explicit at the call site.

fun parseInt(s: String): Result<Int> = runCatching { s.toInt() }
fun main() {
    parseInt("42").onSuccess { println("got $it") }
    parseInt("xx").onFailure { println("oops: ${it.message}") }
}

Chaining Operations

Combine runCatching with map, mapCatching, recover for fluent error pipelines.

fun fetchUserId(): Result<Int> = runCatching { 42 }
fun loadName(id: Int): String = "User-$id"
fun main() {
    val name = fetchUserId()
        .map { loadName(it) }
        .recover { "Anonymous" }
        .getOrNull()
    println(name)
}

Quick Check

Which builder runs a block and wraps the outcome (value or exception) in a Result?

Recap

Result<T> represents success-or-failure. Create with runCatching; transform with map/mapCatching; recover with recover; observe with onSuccess/onFailure; collapse with fold. Great for explicit error pipelines.

Free to start

Learn Kotlin with an AI tutor — free

Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.

Courses
51
Lessons
203

Frequently Asked Questions

Is the “runCatching and Result<T>” lesson free?

Yes — any 3 lessons of the Kotlin Academy learning path, including “runCatching and Result<T>”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The Kotlin Academy course includes 4 lessons in total.

What will I learn in “runCatching and Result<T>”?

Use runCatching to wrap exceptions in Result and process them functionally. You practise Kotlin Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Kotlin Academy?

No prior experience is required. Kotlin Academy on CoddyKit is structured for beginners through advanced learners, so you can start here or from the beginning and move at your own pace. This is lesson 3 of 4.

How long does the “runCatching and Result<T>” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Kotlin Academy lesson?

Yes. Every Kotlin Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. try/catch/finally as an Expression
  2. Creating Custom Exception Classes
  3. runCatching and Result
  4. Re-throwing and Exception Chaining
← Back to Kotlin Academy