Tuesday, December 15, 2009

Some simple Scala null tricks

Scala code often needs to deal with null references, unfortunately. Such is the price of Java interoperability. One of my favourite utility methods is:

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:

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:

1 comment:

Paul said...

The Option apply method has no constraint because the constraint doesn't accomplish anything, and it makes the method less general. Making up an example:

def f[T](x: T) = Option(x).toList

You can't write that method with ? because the constraint would needlessly prevent it.