diff --git a/core/src/main/scala/cats/data/EitherT.scala b/core/src/main/scala/cats/data/EitherT.scala index 1bf4fd75af..516034d7d0 100644 --- a/core/src/main/scala/cats/data/EitherT.scala +++ b/core/src/main/scala/cats/data/EitherT.scala @@ -48,6 +48,13 @@ final case class EitherT[F[_], A, B](value: F[Either[A, B]]) { def valueOr[BB >: B](f: A => BB)(implicit F: Functor[F]): F[BB] = fold(f, identity) + def valueOrF[BB >: B](f: A => F[BB])(implicit F: Monad[F]): F[BB] = { + F.flatMap(value){ + case Left(a) => f(a) + case Right(b) => F.pure(b) + } + } + def forall(f: B => Boolean)(implicit F: Functor[F]): F[Boolean] = F.map(value)(_.forall(f)) def exists(f: B => Boolean)(implicit F: Functor[F]): F[Boolean] = F.map(value)(_.exists(f)) diff --git a/tests/src/test/scala/cats/tests/EitherTSuite.scala b/tests/src/test/scala/cats/tests/EitherTSuite.scala index 8b84f02646..b3063bddbf 100644 --- a/tests/src/test/scala/cats/tests/EitherTSuite.scala +++ b/tests/src/test/scala/cats/tests/EitherTSuite.scala @@ -282,6 +282,12 @@ class EitherTSuite extends CatsSuite { } } + test("valueOrF with Id consistent with Either valueOr") { + forAll{ (eithert: EitherT[Id, String, Int], f: String => Int) => + eithert.valueOrF(f) should === (eithert.value.valueOr(f)) + } + } + test("getOrElse with Id consistent with Either getOrElse") { forAll { (eithert: EitherT[Id, String, Int], i: Int) => eithert.getOrElse(i) should === (eithert.value.getOrElse(i))