Add Result.recover
Similar to getOrElse but returns an Ok of the transformed error
This commit is contained in:
parent
3a3b5415a7
commit
b5aab62af4
@ -29,3 +29,14 @@ inline infix fun <V, E> Result<V, E>.orElse(transform: (E) -> Result<V, E>): Res
|
||||
is Err -> transform(error)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the [transformation][transform] of the [error][Err.error] if this [Result] is [Err],
|
||||
* otherwise this [Ok].
|
||||
*/
|
||||
inline infix fun <V, E> Result<V, E>.recover(transform: (E) -> V): Ok<V> {
|
||||
return when(this) {
|
||||
is Ok -> this
|
||||
is Err -> Ok(transform(error))
|
||||
}
|
||||
}
|
||||
|
@ -41,4 +41,22 @@ internal class OrTest {
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
internal class `recover` {
|
||||
@Test
|
||||
internal fun returnsValueIfOk() {
|
||||
assertEquals(
|
||||
expected = 3000,
|
||||
actual = Ok(3000).recover { 4000 }.get()
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
internal fun returnsTransformedValueIfErr() {
|
||||
assertEquals(
|
||||
expected = 2000,
|
||||
actual = Err(4000).recover { 2000 }.get()
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user