Skip to content
Michael Bull edited this page Mar 16, 2024 · 15 revisions

Mappings from Elm's Result and Result.Extra types to kotlin-result.


<V, E, U> Result<V, E>.map(transform: (V) -> U): Result<U, E>

Apply a function to a Result. If the result is Ok, it will be converted. If the result is an Err, the same error value will propagate through.

val value = Ok(10).map { it + 20 }.get()
// value = 30

<V, E, U> Result<V, E>.andThen(transform: (V) -> Result<U, E>): Result<U, E>

Chain together a sequence of computations that may fail.

val value = Ok(20).andThen { Ok(it + 30) }.andThen { Ok(it + 40) }.get()
// value = 90

<V, E> Result<V, E>.getOr(default: V): V

If the result is Ok return the value, but if the result is an Err then return a given default value.

val value = Err("error").getOr("default")
// value = default

<V, E> Result<V, E>.get(): V?

If the result is Ok return the value, but if the result is an Err then return null.

val value = Ok(230).get()
val error = Err("example").get()
// value = 230
// error = null

<V, E, F> Result<V, E>.mapError(transform: (E) -> F): Result<V, F>

Transform an Err value.

val error = Ok(55).andThen { Err(100) }.mapError { Err(500) }.getError()
// error = 500

Check whether the result is Ok without unwrapping it.

val result = Ok(500)
if (result.isOk) {
    println("Result is ok")
}

Check whether the result is Err without unwrapping it.

val result = Err(500)
if (result.isErr) {
    println("Result is not ok")
}

<V, E> Result<V, E>.getOrElse(transform: (E) -> V): V

Turn a Result<V, E> to a V, by applying the conversion function specified to the E.

val value = Err("hello").getOrElse { "world" }
// value = "world"

<V, E, U> Result<V, E>.mapBoth(success: (V) -> U, failure: (E) -> U): U

Convert a Result<V, E> to a U by applying either a function if the Result is an Err or a function if the Result is Ok. Both of these functions must return the same type.

val value: String = Ok("he").mapBoth(
    success = { "$it succeeded" },
    failure = { "$it failed" }
)
// value = "he succeeded"

<V, E> Iterable<Result<V, E>>.combine(): Result<List<V>, E>

Combine an Iterable of Results into a single Result (holding a List).

val values = combine(
    Ok(20),
    Ok(40),
    Ok(60)
).get()
// values = [ 20, 40, 60 ]

val error = combine(
    Ok(20),
    Err(40),
    Ok(60)
)
// error = Err(40)