From 5f30a73936d675ddc15020591b7c7643bcd23cb4 Mon Sep 17 00:00:00 2001 From: Rohan Shah Date: Thu, 11 Jan 2018 22:51:41 -0500 Subject: [PATCH] Add leftFlatMap to Either (#2149) * Add leftFlatMap to Either syntax * Add tests for Either leftFlatMap --- core/src/main/scala/cats/syntax/either.scala | 5 +++++ tests/src/test/scala/cats/tests/EitherSuite.scala | 12 ++++++++++++ 2 files changed, 17 insertions(+) diff --git a/core/src/main/scala/cats/syntax/either.scala b/core/src/main/scala/cats/syntax/either.scala index bad47ec411..e9d440570d 100644 --- a/core/src/main/scala/cats/syntax/either.scala +++ b/core/src/main/scala/cats/syntax/either.scala @@ -148,6 +148,11 @@ final class EitherOps[A, B](val eab: Either[A, B]) extends AnyVal { case Right(b) => f(b) } + def leftFlatMap[C, BB >: B](f: A => Either[C, BB]): Either[C, BB] = eab match { + case Left(a) => f(a) + case r @ Right(_) => EitherUtil.leftCast(r) + } + def compare[AA >: A, BB >: B](that: Either[AA, BB])(implicit AA: Order[AA], BB: Order[BB]): Int = eab match { case Left(a1) => that match { diff --git a/tests/src/test/scala/cats/tests/EitherSuite.scala b/tests/src/test/scala/cats/tests/EitherSuite.scala index 12f846965b..4d3a791ddd 100644 --- a/tests/src/test/scala/cats/tests/EitherSuite.scala +++ b/tests/src/test/scala/cats/tests/EitherSuite.scala @@ -282,4 +282,16 @@ class EitherSuite extends CatsSuite { } } + test("leftFlatMap consistent with leftMap") { + forAll { (either: Either[String, Int], f: String => String) => + either.leftFlatMap(v => Left(f(v))) should === (either.leftMap(f)) + } + } + + test("leftFlatMap consistent with swap and then flatMap") { + forAll { (either: Either[String, Int], f: String => Either[String, Int]) => + either.leftFlatMap(f) should === (either.swap.flatMap(a => f(a).swap).swap) + } + } + }