Skip to content

Commit

Permalink
Add .toOptionT (#2253)
Browse files Browse the repository at this point in the history
  • Loading branch information
marcodippy authored and Luka Jacobowitz committed May 19, 2018
1 parent 13de346 commit 21c3039
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 1 deletion.
13 changes: 12 additions & 1 deletion core/src/main/scala/cats/syntax/option.scala
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package cats
package syntax

import cats.data.{Ior, Validated, ValidatedNel}
import cats.data.{Ior, OptionT, Validated, ValidatedNel}
import cats.syntax.OptionOps.LiftToPartiallyApplied

trait OptionSyntax {
Expand Down Expand Up @@ -188,6 +188,17 @@ final class OptionOps[A](val oa: Option[A]) extends AnyVal {
*/
def liftTo[F[_]]: LiftToPartiallyApplied[F, A] = new LiftToPartiallyApplied(oa)

/**
* Transform the `Option` into a [[cats.data.OptionT]] while lifting it into the specified Applicative.
*
* {{{
* scala> import cats.implicits._
* scala> val op: Option[Int] = Some(3)
* scala> op.toOptionT[List]
* res0: cats.data.OptionT[List, Int] = OptionT(List(Some(3)))
* }}}
*/
def toOptionT[F[_]: Applicative]: OptionT[F, A] = OptionT.fromOption(oa)
}

object OptionOps {
Expand Down
5 changes: 5 additions & 0 deletions tests/src/test/scala/cats/tests/OptionSuite.scala
Original file line number Diff line number Diff line change
Expand Up @@ -94,4 +94,9 @@ class OptionSuite extends CatsSuite {
val bomb: Eval[Option[Int]] = Later(sys.error("boom"))
none[Int].map2Eval(bomb)(_ + _).value should === (None)
}

test("toOptionT consistency"){
List(false) should === (1.some.toOptionT[List].isEmpty)
List(true) should === (Option.empty[Int].toOptionT[List].isEmpty)
}
}

0 comments on commit 21c3039

Please sign in to comment.