The apply method of the Option singleton object has a nice way to convert null to None (see Option.scala):
def apply[A](x: A): Option[A] = if (x == null) None else Some(x)
Hence, you can do Option(null) and you'll get None.
A simple example that handles null in a safe way:
val maybeNull = someJavaMethodThatMightReturnNull(42)
Option(maybeNull).foreach(println)
On the other hand, if you do Some(null) you'll get back Some(null).
No comments:
Post a Comment