Thursday, April 7, 2016

Handling null in Scala

When you are using Java APIs, you might find yourself in the situation that you have to deal with null. In plain Scala, usually you wouldn't use null, but use an Option instead.

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