Skip to content

Commit

Permalink
Merge pull request #946 from MaxWorgan/ISSUE-935
Browse files Browse the repository at this point in the history
Added OptionT.none, resolving #935
  • Loading branch information
stew committed Apr 1, 2016
2 parents a8ba943 + b3e8ac7 commit 08d843d
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 0 deletions.
7 changes: 7 additions & 0 deletions core/src/main/scala/cats/data/OptionT.scala
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,13 @@ object OptionT extends OptionTInstances {
def pure[F[_], A](a: A)(implicit F: Applicative[F]): OptionT[F, A] =
OptionT(F.pure(Some(a)))

/** An alias for pure */
def some[F[_], A](a: A)(implicit F: Applicative[F]): OptionT[F, A] =
pure(a)

def none[F[_], A](implicit F: Applicative[F]) : OptionT[F, A] =
OptionT(F.pure(None))

/**
* Transforms an `Option` into an `OptionT`, lifted into the specified `Applicative`.
*
Expand Down
17 changes: 17 additions & 0 deletions docs/src/main/tut/optiont.md
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,23 @@ val result: Future[Option[String]] = ot.value // Future(Some("Hello Jane Doe"))
```

## From `A` to `OptionT[F,A]`

If you have only an `A` and you wish to *lift* it into an `OptionT[F,A]` assuming you have an [`Applicative`]({{ site.baseurl }}/tut/applicative.html) instance for `F` you can use `some` which is an alias for `pure`. There also exists a `none` method which can be used to create an `OptionT[F,A]`, where the `Option` wrapped `A` type is actually a `None`:

```tut:silent
import cats.std.future._
val greet: OptionT[Future,String] = OptionT.pure("Hola!")
val greetAlt: OptionT[Future,String] = OptionT.some("Hi!")
val failedGreet: OptionT[Future,String] = OptionT.none
```


## Beyond map

Sometimes the operation you want to perform on an `Future[Option[String]]` might not be as simple as just wrapping the `Option` method in a `Future.map` call. For example, what if we want to greet the customer with their custom greeting if it exists but otherwise fall back to a default `Future[String]` greeting? Without `OptionT`, this implementation might look like:
Expand Down
4 changes: 4 additions & 0 deletions tests/src/test/scala/cats/tests/OptionTTests.scala
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,10 @@ class OptionTTests extends CatsSuite {
OptionT[Xor[String, ?], Int](xor).show should === ("Xor.Right(Some(1))")
}

test("none") {
OptionT.none[List,Int] should === (OptionT[List,Int](List(None)))
}

test("implicit Show[OptionT] instance and explicit show method are consistent") {
forAll { optionT: OptionT[List, Int] =>
optionT.show should === (implicitly[Show[OptionT[List, Int]]].show(optionT))
Expand Down

0 comments on commit 08d843d

Please sign in to comment.