Skip to content

Commit

Permalink
Add Maybe.fromNullable for null -> Empty
Browse files Browse the repository at this point in the history
I consider it a major oversight that I failed to address Java interop
where `null` is a possibility in my original implementation of Maybe. This
commit adds `Maybe.fromNullable` which works similarly to `Option.apply`. If it is
passed `null` it returns `Empty` but otherwise just wraps a value in
`Just`.

The name `fromNullable` was chosen to be explicit about the fact that it
accepts a null input. It was determined that `Maybe.apply` would be a
bad choice because it might be expected to be the same as Maybe's
`point` (which it is not).

(cherry picked from commit 883ade8)
  • Loading branch information
ceedubs authored and xuwei-k committed Jan 31, 2015
1 parent 60355a3 commit c17a756
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 0 deletions.
4 changes: 4 additions & 0 deletions core/src/main/scala/scalaz/Maybe.scala
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,10 @@ object Maybe extends MaybeInstances with MaybeFunctions {
def to[A](fa: Option[A]) = std.option.toMaybe(fa)
def from[A](ga: Maybe[A]) = ga.toOption
}

/** Wrap a value in Just, or return Empty if the value is null */
final def fromNullable[A](a: A): Maybe[A] =
if (null == a) empty else just(a)
}

sealed trait MaybeFunctions {
Expand Down
8 changes: 8 additions & 0 deletions tests/src/test/scala/scalaz/MaybeTests.scala
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ object MaybeTest extends SpecLite {
import scalaz.scalacheck.ScalazProperties._
import scalaz.scalacheck.ScalazArbitrary._
import std.anyVal._
import std.string._
import syntax.equal._

import Maybe._
Expand Down Expand Up @@ -82,6 +83,13 @@ object MaybeTest extends SpecLite {

"just orElse is just" ! forAll { (x: Int, m: Maybe[Int]) => just(x).orElse(m).isJust }

"fromNullable(null) is Empty" ! check {
val s: String = null
Maybe.fromNullable(s).isEmpty
}

"fromNullable(notNull) is just" ! forAll { (s: String) => Maybe.fromNullable(s) must_=== just(s) }

object instances {
def equal[A: Equal] = Equal[Maybe[A]]
def order[A: Order] = Order[Maybe[A]]
Expand Down

0 comments on commit c17a756

Please sign in to comment.