I don't know about scalaz, but in the standard library your only choice really is to filter out the null
value. map
simply maps A => B
and expects that B
will not be null
.
Example:
object HasNull {
def getNull: Any = null
}
scala> Option(HasNull).map(_.getNull).filter(_ != null)
res24: Option[Any] = None
Or
scala> Option(HasNull).flatMap(a => Option(a.getNull))
res25: Option[Any] = None
Alternatively, you can use a little implicit magic to avoid the Option
boilerplate:
implicit def toOpt[A](a: A): Option[A] = Option(a)
scala> Option(HasNull).flatMap(_.getNull)
res3: Option[Any] = None
Using flatMap
still is the key, because it expects an Option[B]
. But getNull
is of type B
, so the implicit conversion will be used, which will wrap the nullable in Option.apply
again.