Add flatten
Converts from Result<Result<V, E>, E> to Result<V, E> See: https://doc.rust-lang.org/std/result/enum.Result.html#method.flatten
This commit is contained in:
parent
73a71154e9
commit
5ded43d3b4
@ -167,6 +167,15 @@ public inline infix fun <V, E, U> Result<V, E>.flatMap(transform: (V) -> Result<
|
||||
return andThen(transform)
|
||||
}
|
||||
|
||||
/**
|
||||
* Maps this [Result<Result<V, E>, E>][Result] to [Result<V, E>][Result].
|
||||
*
|
||||
* - Rust: [Result.flatten](https://doc.rust-lang.org/std/result/enum.Result.html#method.flatten)
|
||||
*/
|
||||
public inline fun <V, E> Result<Result<V, E>, E>.flatten(): Result<V, E> {
|
||||
return andThen { it }
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the [transformation][transform] of the [value][Ok.value] if this [Result] is [Ok]
|
||||
* and satisfies the given [predicate], otherwise this [Result].
|
||||
|
@ -176,6 +176,54 @@ class MapTest {
|
||||
}
|
||||
}
|
||||
|
||||
class Flatten {
|
||||
|
||||
@Test
|
||||
fun returnsFlattenedValueIfOk() {
|
||||
val result = Ok(Ok("hello"))
|
||||
|
||||
assertEquals(
|
||||
expected = Ok("hello"),
|
||||
actual = result.flatten()
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun returnsFlattenedErrIfErr() {
|
||||
val result = Ok(Err(6))
|
||||
|
||||
assertEquals(
|
||||
expected = Err(6),
|
||||
actual = result.flatten()
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun returnsErrIfFlatErr() {
|
||||
val result = Err(6)
|
||||
|
||||
assertEquals(
|
||||
expected = Err(6),
|
||||
actual = result.flatten()
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun returnsFlattenNestedResult() {
|
||||
val result = Ok(Ok(Ok("hello")))
|
||||
|
||||
assertEquals(
|
||||
expected = Ok(Ok("hello")),
|
||||
actual = result.flatten()
|
||||
)
|
||||
|
||||
assertEquals(
|
||||
expected = Ok("hello"),
|
||||
actual = result.flatten().flatten()
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
class ToErrorIfNull {
|
||||
|
||||
@Test
|
||||
|
Loading…
Reference in New Issue
Block a user