Add getErrorOrElse

Matches getOrElse signature with respect to the error.
This commit is contained in:
Michael Bull 2017-11-22 23:25:11 +00:00
parent ad7adacf39
commit 5d5195af9d
2 changed files with 23 additions and 0 deletions

View File

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

View File

@ -64,4 +64,16 @@ internal class GetTest {
val value = Err("hello").getOrElse { "world" } val value = Err("hello").getOrElse { "world" }
assertThat(value, equalTo("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"))
}
} }