Add getErrorOrElse
Matches getOrElse signature with respect to the error.
This commit is contained in:
parent
ad7adacf39
commit
5d5195af9d
@ -66,3 +66,14 @@ infix inline fun <V, E> Result<V, E>.getOrElse(transform: (E) -> V): V {
|
||||
is Err -> transform(error)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param transform The transformation to apply to the [value][Ok.value].
|
||||
* @return The [error][Err.error] if [Err], otherwise the [transformed][transform] [value][Ok.value].
|
||||
*/
|
||||
infix inline fun <V, E> Result<V, E>.getErrorOrElse(transform: (V) -> E): E {
|
||||
return when (this) {
|
||||
is Ok -> transform(value)
|
||||
is Err -> error
|
||||
}
|
||||
}
|
||||
|
@ -64,4 +64,16 @@ internal class GetTest {
|
||||
val value = Err("hello").getOrElse { "world" }
|
||||
assertThat(value, equalTo("world"))
|
||||
}
|
||||
|
||||
@Test
|
||||
internal fun `getErrorOrElse should return the transformed result value if ok`() {
|
||||
val error = Ok("hello").getErrorOrElse { "world" }
|
||||
assertThat(error, equalTo("world"))
|
||||
}
|
||||
|
||||
@Test
|
||||
internal fun `getErrorOrElse should return the result error if not ok`() {
|
||||
val error = Err("hello").getErrorOrElse { "world" }
|
||||
assertThat(error, equalTo("hello"))
|
||||
}
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user