Skip to content

Haskell

Michael Bull edited this page Mar 11, 2026 · 16 revisions

Mappings from Haskell's Either and Bifunctor types to kotlin-result.


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

If the value is Ok(V), apply the first function to V; if it is Err(E), apply the second function to E.

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

<V, E, R : Result<V, E>> valuesOf(vararg results: R): List<V>

Extracts from a set of Results all the Ok elements. All the Ok elements are extracted in order.

val values: List<String> = valuesOf(
    Ok("hello"),
    Ok("world")
)
// values = [ "hello", "world" ]

<V, E, R : Result<V, E>> errorsOf(vararg results: R): List<E>

Extracts from a set of Results all the Err elements. All the Err elements are extracted in order.

val errors: List<String> = errorsOf(
    Err("error 1"),
    Err("error 2")
)
// errors = [ "error 1", "error 2" ]

Return true if the result is Ok, false otherwise.

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

Return true if the result is Err, false otherwise.

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

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

Return the value of an Ok-result or a default value otherwise.

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

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

Return the error of an Err-result or a default value otherwise.

val error: String = Ok("hello").getErrorOr("world")
// error = "world"

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

Partitions an Iterable of Result into a Pair of two Lists. All the Ok elements are extracted, in order, to the first value of the Pair. Similarly the Err elements are extracted to the second value of the Pair.

val pairs: Pair<List<String>, List<String>> = partition(
    Err("c#"),
    Ok("haskell"),
    Err("java"),
    Ok("f#"),
    Err("c"),
    Ok("elm"),
    Err("lua"),
    Ok("clojure"),
    Err("javascript")
)
// pairs.first = [ "haskell", "f#", "elm", "clojure" ]
// pairs.second = [ "c#", "java", "c", "lua", "javascript"]

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

Map over both arguments at the same time.

val result: Result<String, String> = Err("the reckless").mapEither(
    success = { "the wild youth" },
    failure = { "the truth" }
)

// result = Err("the truth")

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

Map covariantly over the first argument (the Ok value).

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

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

Map covariantly over the second argument (the Err value).

val result = Err(100).mapError { it * 5 }
// result = Err(500)

Clone this wiki locally