-
Notifications
You must be signed in to change notification settings - Fork 64
Scala
Michael Bull edited this page Mar 16, 2024
·
13 revisions
Mappings from Scala's Either
and MergeableEither
types to kotlin-result
.
<V, E, U> Result<V, E>.mapBoth(success: (V) -> U, failure: (E) -> U): U
Applies success
if this is Ok
or failure
if this is an Err
.
val result: Result<Int, Exception> = possiblyFailingOperation()
val message: String = result.mapBoth(
success = { "Operation produced value: ${it.value}" },
failure = { "Operation failed with ${it.message}" }
)
logger.info(message)
<V, E> Result<V, E>.getOr(default: V): V
Returns the value
from this Ok
or the given argument if this is an Err
.
Ok(12).getOr(17) // 12
Err(12).getOr(17) // 17
<V, E, U> Result<V, E>.andThen(transform: (V) -> Result<U, E>): Result<U, E>
The given function is applied if this is Ok
.
Ok(12).andThen { "flower" } // Result: Ok("flower")
Err(12).andThen { "flower" } // Result: Err(12)
<V, E> Result<V, E>.get(): V?
Returns the value if it exists or null
if this is an Err
.
<V : U, E : U, U> Result<V, E>.merge(): U
Allows use of a merge
method to extract values from Result
instances regardless of whether they are Ok
or Err
.
val ok = Ok(listOf(1, 2, 3)) as Result<List<Int>, Set<Int>>
val err = Err(setOf(4, 5, 6)) as Result<List<Int>, Set<Int>>
val mergedOk: Collection<Int> = ok.merge() // listOf<Int>(1, 2, 3)
val mergedErr: Collection<Int> = err.merge() // setOf<Int>(4, 5, 6)