Skip to content

Commit

Permalink
Add handleErr method
Browse files Browse the repository at this point in the history
  • Loading branch information
natsukagami committed Apr 12, 2024
1 parent 5f55242 commit 9fed188
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 0 deletions.
10 changes: 10 additions & 0 deletions src/main/scala/dotty/result/package.scala
Original file line number Diff line number Diff line change
Expand Up @@ -361,6 +361,16 @@ object Result:
def flatMap[U](f: T => Result[U, E]) = r match
case Ok(value) => f(value)
case err @ Err(_) => err

/** Returns the output of `f` from applying it to the [[Err]] case error,
* otherwise keeping the [[Ok]] case. Similar to [[flatMap]], but on the
* [[Err]] case.
* @group transform
*/
def handleErr[E1](f: E => Result[T, E1]) = r match
case ok: Ok[T] => ok
case Err(error) => f(error)

end extension

extension [T, E](r: Result[Result[T, E], E])
Expand Down
3 changes: 3 additions & 0 deletions src/test/scala/result/Result.scala
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,9 @@ class ResultTest extends munit.FunSuite {
assertEquals(ok.flatMap(v => Err("pew")), Err("pew"))
assertEquals(err.flatMap(v => Ok(v + 1)), err)

assertEquals(ok.handleErr(_ => err), ok)
assertEquals(err.handleErr(_ => ok), ok)

val sum = for
a <- ok
b <- ok
Expand Down

0 comments on commit 9fed188

Please sign in to comment.