Add getErrorOr

Matches Haskell's Either.fromRight
This commit is contained in:
Michael Bull 2017-10-21 18:10:08 +01:00
parent eea45b3c88
commit be2fa210cc
6 changed files with 29 additions and 6 deletions

View File

@ -23,6 +23,7 @@ fun <V, E> Result<V, E>.getError(): E? {
/** /**
* - Elm: [Result.withDefault](http://package.elm-lang.org/packages/elm-lang/core/latest/Result#withDefault) * - Elm: [Result.withDefault](http://package.elm-lang.org/packages/elm-lang/core/latest/Result#withDefault)
* - Haskell: [Result.fromLeft](https://hackage.haskell.org/package/base-4.10.0.0/docs/Data-Either.html#v:fromLeft)
* - Rust: [Result.unwrap_or](https://doc.rust-lang.org/std/result/enum.Result.html#method.unwrap_or) * - Rust: [Result.unwrap_or](https://doc.rust-lang.org/std/result/enum.Result.html#method.unwrap_or)
*/ */
infix fun <V, E> Result<V, E>.getOr(default: V): V { infix fun <V, E> Result<V, E>.getOr(default: V): V {
@ -32,6 +33,16 @@ infix fun <V, E> Result<V, E>.getOr(default: V): V {
} }
} }
/**
* - Haskell: [Result.fromRight](https://hackage.haskell.org/package/base-4.10.0.0/docs/Data-Either.html#v:fromRight)
*/
infix fun <V, E> Result<V, E>.getErrorOr(default: E): E {
return when (this) {
is Ok -> default
is Error -> error
}
}
/** /**
* - Elm: [Result.extract](http://package.elm-lang.org/packages/circuithub/elm-result-extra/1.4.0/Result-Extra#extract) * - Elm: [Result.extract](http://package.elm-lang.org/packages/circuithub/elm-result-extra/1.4.0/Result-Extra#extract)
* - Rust: [Result.unwrap_or_else](https://doc.rust-lang.org/src/core/result.rs.html#735-740) * - Rust: [Result.unwrap_or_else](https://doc.rust-lang.org/src/core/result.rs.html#735-740)

View File

@ -43,6 +43,18 @@ internal class GetTest {
assertThat(value, equalTo("default")) assertThat(value, equalTo("default"))
} }
@Test
internal fun `getErrorOr should return the default value if ok`() {
val error = ok("hello").getErrorOr("world")
assertThat(error, equalTo("world"))
}
@Test
internal fun `getErrorOr should return the result error if not ok`() {
val error = err("hello").getErrorOr("world")
assertThat(error, equalTo("hello"))
}
@Test @Test
internal fun `getOrElse should return the result value if ok`() { internal fun `getOrElse should return the result value if ok`() {
val value = ok("hello").getOrElse { "world" } val value = ok("hello").getOrElse { "world" }

View File

@ -2,7 +2,7 @@ package com.mikebull94.result
import com.natpryce.hamkrest.assertion.assertThat import com.natpryce.hamkrest.assertion.assertThat
import com.natpryce.hamkrest.equalTo import com.natpryce.hamkrest.equalTo
import org.junit.jupiter.api.Assertions.* import org.junit.jupiter.api.Assertions.assertThrows
import org.junit.jupiter.api.Test import org.junit.jupiter.api.Test
internal class ResultIteratorTest { internal class ResultIteratorTest {