-
Notifications
You must be signed in to change notification settings - Fork 64
Haskell
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 Error(E)
, apply the second function to E
.
val value: String = ok("he").mapBoth(
success = { "$it succeeded" },
failure = { "$it failed" }
)
// value = "he succeeded"
<V, E> Iterable<Result<V, E>>.getAll(): List<V>
Extracts from an Iterable
of Result
all the Ok
elements. All the Ok
elements are extracted in order.
val values: List<String> = getAll(
ok("hello"),
ok("world")
)
// values = [ "hello", "world" ]
<V, E> Iterable<Result<V, E>>.getAllErrors(): List<E>
Extracts from an Iterable
of Result
all the Error
elements. All the Error
elements are extracted in order.
val errors: List<String> = getAllErrors(
err("error 1"),
err("error 2")
)
// errors = [ "error 1", "error 2" ]
Return true
if the result is a Ok
, false
otherwise.
val result = ok(500)
if (result is Ok) {
println("Result is ok")
}
Return true
if the result is a Error
, false
otherwise.
val result = error(600)
if (result is Error) {
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 Error
-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 List
s. All the Ok
elements are extracted, in order, to the first value of the Pair
. Similarly the Error
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"]
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 = Error("the truth")