Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add .toOptionT to option syntax #2253

Merged
merged 1 commit into from
May 19, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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)
}
}