From 9fed1885f33836b217e3c7df35edbc439764dd89 Mon Sep 17 00:00:00 2001 From: Natsu Kagami Date: Fri, 12 Apr 2024 15:09:38 +0200 Subject: [PATCH] Add handleErr method --- src/main/scala/dotty/result/package.scala | 10 ++++++++++ src/test/scala/result/Result.scala | 3 +++ 2 files changed, 13 insertions(+) diff --git a/src/main/scala/dotty/result/package.scala b/src/main/scala/dotty/result/package.scala index 7493019..a1d4a70 100644 --- a/src/main/scala/dotty/result/package.scala +++ b/src/main/scala/dotty/result/package.scala @@ -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]) diff --git a/src/test/scala/result/Result.scala b/src/test/scala/result/Result.scala index bc3f592..78dffce 100644 --- a/src/test/scala/result/Result.scala +++ b/src/test/scala/result/Result.scala @@ -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