Add Result.recover

Similar to getOrElse but returns an Ok of the transformed error
This commit is contained in:
Michael Bull 2018-11-01 11:42:09 +00:00
parent 3a3b5415a7
commit b5aab62af4
2 changed files with 29 additions and 0 deletions

View File

@ -29,3 +29,14 @@ inline infix fun <V, E> Result<V, E>.orElse(transform: (E) -> Result<V, E>): Res
is Err -> transform(error) 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))
}
}

View File

@ -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()
)
}
}
} }