Scala code often needs to deal with null references, unfortunately. Such is the price of Java interoperability. One of my favourite utility methods is:
def ?[A <: AnyRef](ref: A): Option[A] = if (ref eq null) None else Some(ref) // e.g. val value = ?(javaCallThatMayReturnNull()).getOrElse(defaultValue)
Scala 2.8 offers this using Option(ref)
instead of
?(ref)
. However, I can’t figure out why the Scala 2.8 method
accepts non-reference values as well.
Another simple thing that may come in handy is an extractor for non-null values:
object NotNull { def unapply[A <: AnyRef](ref: A): Option[A] = if (ref eq null) None else Some(ref) }
What’s the advantage of using an extractor? Say you have a collection of references, some of which may be null, and you want to ignore the null references:
val xs = List("a", null, "b", null, null, "c", null) // prints "List(a, b, c)" println(for (NotNull(x) <- xs) yield x)
Comments !