Michael Bull 2020-08-26 17:22:55 +01:00
parent 30b5d918c7
commit 09d341ae6d
2 changed files with 31 additions and 0 deletions

View File

@ -120,3 +120,16 @@ inline infix fun <V, E> Result<V, E>.getErrorOrElse(transform: (V) -> E): E {
is Err -> error
}
}
/**
* Merges this [Result<V, E>][Result] to [U], returning the [value][Ok.value] if this [Result] is [Ok], otherwise the
* [error][Err.error].
*
* - Scala: [MergeableEither.merge](https://www.scala-lang.org/api/2.12.0/scala/util/Either$$MergeableEither.html#merge:A)
*/
fun <V : U, E : U, U> Result<V, E>.merge(): U {
return when (this) {
is Ok -> value
is Err -> error
}
}

View File

@ -106,4 +106,22 @@ class GetTest {
)
}
}
class Merge {
@Test
fun returnsValueIfOk() {
assertEquals(
expected = listOf(1, 2, 3),
actual = Ok(listOf(1, 2, 3)).merge()
)
}
@Test
fun returnsErrorIfErr() {
assertEquals(
expected = setOf(4, 5, 6),
actual = Err(setOf(4, 5, 6)).merge()
)
}
}
}