Kotlin getOrDefault() function
In Kotlin, the getOrDefault()
function is used to retrieve the value from a Result
instance if this instance represents success, or provide a default value if the Result is a failure.
This function is particularly useful when working with the Result
type, which represents either a successful value or a failure with an error. It allows you to handle errors more gracefully by providing a default value in case of failure.
In this tutorial, we’ll explore the syntax of the getOrDefault()
function and provide examples of its usage in Kotlin.
Syntax
The syntax of the getOrDefault()
function is:
fun <R, T : R> Result<T>.getOrDefault(defaultValue: R): R
The getOrDefault()
function takes a default value parameter of type R
and returns the success value if the result is a success or the default value if it’s an error.
Examples for getOrDefault() function
1. Retrieving Value from Successful Result
In this example, we’ll use getOrDefault()
to retrieve the value from a successful Result
instance.
Kotlin Program
fun main() {
val result = Result.success(42)
// Retrieving the value or using a default value of 0
val value = result.getOrDefault(0)
// Printing the result
println("Result value: $value")
}
Output
Result value: 42
2. Handling Error with Default Value
In this example, we’ll use getOrDefault()
to handle the case where the result is a failure.
Kotlin Program
fun main() {
val result: Result<Int> = Result.failure(Exception("An error occurred"))
// Retrieving the value or using a default value of 0
val value = result.getOrDefault(0)
// Printing the result
println("Result value: $value")
}
Output
Result value: 0
Summary
In this tutorial, we’ve covered the getOrDefault()
function in Kotlin, its syntax, and how to use it for retrieving values from a Result
instance with a default value for failure cases.