The Result Type
In this page:
Creating a Result with runCatching
runCatching { } executes a block of code and wraps the outcome in a Result: a caught exception becomes a failure, and a normal return value becomes a success.
Example: Creating a Result with runCatching
fun main() {
val result = runCatching { "42".toInt() }
println("Success: ${result.isSuccess}")
}
Login to try C/C++/Java/PHP code in the editor
Extracting Values Safely
.getOrNull() returns the successful value or null on failure, while .getOrElse { } lets you supply a fallback computed from the failure itself.
Example: Extracting Values Safely
fun main() {
val goodResult = runCatching { "42".toInt() }
val badResult = runCatching { "abc".toInt() }
println("Good: ${goodResult.getOrNull()}")
println("Bad with fallback: ${badResult.getOrElse { -1 }}")
}
Login to try C/C++/Java/PHP code in the editor
Handling Both Outcomes with fold
.fold(onSuccess, onFailure) lets you handle a success and a failure case together in one expression, producing a single unified result from either branch.
Example: Handling Both Outcomes with fold
fun main() {
val result = runCatching { "abc".toInt() }
val message = result.fold(
onSuccess = { "Parsed: $it" },
onFailure = { "Failed: ${it.message}" }
)
println(message)
}
Login to try C/C++/Java/PHP code in the editor
Result in Function Return Types
A function can return Result<T> directly instead of throwing, making failure an explicit, visible part of its return type that callers must consciously handle. (Declaring Result as an explicit function return type requires Kotlin 1.5+; on older versions the same value can still be computed and stored in a val, as shown below.)
Example: Result in Function Return Types
fun main() {
val input = "-5"
val result: Result<Int> = runCatching {
val age = input.toInt()
require(age >= 0) { "Age cannot be negative" }
age
}
println(result.fold(onSuccess = { "Age: $it" }, onFailure = { "Invalid: ${it.message}" }))
}
Login to try C/C++/Java/PHP code in the editor
- Forgetting
Resultis designed as a return-value alternative to exceptions, not a replacement for usingtry/catchwhen calling code that itself throws. - Not checking
.isSuccess/.isFailure(or using.fold/.getOrElse) and instead calling.getOrThrow()immediately, defeating the purpose of a non-throwing result. - Assuming
Resultcan hold any kind of computation state (like 'still loading'); it strictly represents success or failure, not other states.
Result<T>represents either a successful value or a failure, without needing atry/catchat the call site.runCatching { }runs a block and wraps its outcome in aResult, catching any thrown exception into the failure case..getOrNull(),.getOrElse { }, and.getOrThrow()extract the value from aResultin different ways..fold(onSuccess, onFailure)handles both outcomes of aResultin a single expression.
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: