Skip to content

Commit

Permalink
Add getErrorOrElse
Browse files Browse the repository at this point in the history
Matches getOrElse signature with respect to the error.
  • Loading branch information
michaelbull committed Nov 22, 2017
1 parent ad7adac commit 5d5195a
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 0 deletions.
11 changes: 11 additions & 0 deletions src/main/kotlin/com/github/michaelbull/result/Get.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
}
12 changes: 12 additions & 0 deletions src/test/kotlin/com/github/michaelbull/result/GetTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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"))
}
}

0 comments on commit 5d5195a

Please sign in to comment.