Kotlin

Result Type — Safe Error-Returning APIs

admin by @admin ADMIN
15m ago
Jun 1, 2026
Public
0 0 up · 0 down Sign in to vote
`Result<T>` wraps "success or thrown exception" without forcing the caller into try/catch. `runCatching { ... }` is the standard producer.
Kotlin
Raw
fun parseUser(raw: String): Result<Pair<String, Int>> = runCatching {
    val (name, ageStr) = raw.split(",")
    require(ageStr.toIntOrNull() != null) { "age must be int" }
    name to ageStr.toInt()
}

fun main() {
    val r1 = parseUser("Alice,30")
    println(r1)                                  // Success((Alice, 30))

    val r2 = parseUser("Bob,xyz")
    println(r2)                                  // Failure(IllegalArgumentException ...)

    // map / mapCatching transform success values
    val agePlusOne: Result<Int> = r1.map { it.second + 1 }
    println(agePlusOne)                          // Success(31)

    // fold — handle both branches
    val display = r2.fold(
        onSuccess = { (name, age) -> "$name is $age" },
        onFailure = { ex -> "Error: ${ex.message}" }
    )
    println(display)                             // Error: age must be int

    // Get-or-default style
    val safeAge = parseUser("Cara,40").getOrNull()?.second ?: -1
    println(safeAge)                             // 40
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.