Skip to content

Commit

Permalink
andThenRecover function added
Browse files Browse the repository at this point in the history
  • Loading branch information
Jhabkin committed Jan 23, 2024
1 parent cb6edff commit dfab2bd
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,23 @@ public inline infix fun <V, E, U> Result<V, E>.andThen(transform: (V) -> Result<
}
}

/**
* Returns the [transformation][transform] of the [error][Err.error] if this [Result] is [Err],
* otherwise this [Result].
*/
public inline fun <V, E> Result<V, E>.andThenRecover(
transform: (E) -> Result<V, E>
): Result<V, E> {
contract {
callsInPlace(transform, InvocationKind.AT_MOST_ONCE)
}

return when (this) {
is Ok -> this
is Err -> transform(error)
}
}

/**
* Returns the [transformation][transform] of the [error][Err.error] if this [Result] is [Err] and
* satisfies the given [predicate], otherwise this [Result].
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,24 @@ class AndTest {
}
}

class AndThenRecover {
@Test
fun returnsValueIfOk() {
assertEquals(
expected = 5,
actual = Ok(5).andThenRecover { Ok(7) }.get()
)
}

@Test
fun returnsTransformValueIfErr() {
assertSame(
expected = 20,
actual = Err(AndError).andThenRecover { Ok(20) }.get()
)
}
}

class AndThenRecoverIf {
@Test
fun returnsValueIfOk() {
Expand Down

0 comments on commit dfab2bd

Please sign in to comment.