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:
Michael Bull 2024-03-02 16:51:45 +00:00
parent 73a71154e9
commit 5ded43d3b4
2 changed files with 57 additions and 0 deletions

View File

@ -167,6 +167,15 @@ public inline infix fun <V, E, U> Result<V, E>.flatMap(transform: (V) -> Result<
return andThen(transform) 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] * Returns the [transformation][transform] of the [value][Ok.value] if this [Result] is [Ok]
* and satisfies the given [predicate], otherwise this [Result]. * and satisfies the given [predicate], otherwise this [Result].

View File

@ -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 { class ToErrorIfNull {
@Test @Test