Skip to content

Commit

Permalink
Merge pull request #1327 from markus1189/xort-from-option
Browse files Browse the repository at this point in the history
Add EitherT.fromOption
  • Loading branch information
kailuowang authored Aug 24, 2016
2 parents 3ca2309 + 50db00c commit e63c305
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 0 deletions.
18 changes: 18 additions & 0 deletions core/src/main/scala/cats/data/EitherT.scala
Original file line number Diff line number Diff line change
Expand Up @@ -252,6 +252,24 @@ trait EitherTFunctions {
def apply[E, A](either: Either[E, A])(implicit F: Applicative[F]): EitherT[F, E, A] =
EitherT(F.pure(either))
}

/** Transforms an `Option` into an `EitherT`, lifted into the specified `Applicative` and using
* the second argument if the `Option` is a `None`.
* {{{
* scala> import cats.implicits._
* scala> val o: Option[Int] = None
* scala> EitherT.fromOption[List](o, "Answer not known.")
* res0: EitherT[List, String, Int] = EitherT(List(Left(Answer not known.)))
* scala> EitherT.fromOption[List](Some(42), "Answer not known.")
* res1: EitherT[List, String, Int] = EitherT(List(Right(42)))
* }}}
*/
final def fromOption[F[_]]: FromOptionPartiallyApplied[F] = new FromOptionPartiallyApplied

final class FromOptionPartiallyApplied[F[_]] private[EitherTFunctions] {
def apply[E, A](opt: Option[A], ifNone: => E)(implicit F: Applicative[F]): EitherT[F, E, A] =
EitherT(F.pure(Either.fromOption(opt, ifNone)))
}
}

private[data] abstract class EitherTInstances extends EitherTInstances1 {
Expand Down
6 changes: 6 additions & 0 deletions tests/src/test/scala/cats/tests/EitherTTests.scala
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,12 @@ class EitherTTests extends CatsSuite {
}
}

test("fromOption isLeft consistent with Option.isEmpty") {
forAll { (o: Option[Int], s: String) =>
EitherT.fromOption[Id](o, s).isLeft should === (o.isEmpty)
}
}

test("isLeft negation of isRight") {
forAll { (eithert: EitherT[List, String, Int]) =>
eithert.isLeft should === (eithert.isRight.map(! _))
Expand Down

0 comments on commit e63c305

Please sign in to comment.