Skip to content

Commit

Permalink
Merge pull request #1454 from edmundnoble/eitheridops
Browse files Browse the repository at this point in the history
Either .left, .right syntax
  • Loading branch information
kailuowang authored Nov 7, 2016
2 parents 2fd55c5 + 2538b0e commit 9af39fb
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 0 deletions.
10 changes: 10 additions & 0 deletions core/src/main/scala/cats/syntax/either.scala
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ trait EitherSyntax {
implicit def catsSyntaxLeft[A, B](left: Left[A, B]): LeftOps[A, B] = new LeftOps(left)

implicit def catsSyntaxRight[A, B](right: Right[A, B]): RightOps[A, B] = new RightOps(right)

implicit def catsSyntaxEitherId[A](a: A): EitherIdOps[A] = new EitherIdOps(a)
}

final class EitherOps[A, B](val eab: Either[A, B]) extends AnyVal {
Expand Down Expand Up @@ -306,6 +308,14 @@ final class RightOps[A, B](val right: Right[A, B]) extends AnyVal {
def leftCast[C]: Either[C, B] = right.asInstanceOf[Either[C, B]]
}

final class EitherIdOps[A](val obj: A) extends AnyVal {
/** Wrap a value in `Left`. */
def asLeft[B]: Either[A, B] = Left(obj)

/** Wrap a value in `Right`. */
def asRight[B]: Either[B, A] = Right(obj)
}

/** Convenience methods to use `Either` syntax inside `Either` syntax definitions. */
private[cats] object EitherUtil {
def leftCast[A, B, C](right: Right[A, B]): Either[C, B] =
Expand Down
7 changes: 7 additions & 0 deletions tests/src/test/scala/cats/tests/EitherTests.scala
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,13 @@ class EitherTests extends CatsSuite {
}
}

test("Left/Right id syntax") {
forAll { (e: Int) =>
assert(Left[Int, String](e) === e.asLeft[String])
assert(Right[String, Int](e) === e.asRight[String])
}
}

test("implicit instances resolve specifically") {
val eq = catsStdEqForEither[Int, String]
assert(!eq.isInstanceOf[PartialOrder[_]])
Expand Down

0 comments on commit 9af39fb

Please sign in to comment.