Wednesday 28 December 2011

Handling Java nulls in Scala

Null handling in Scala can be painful, to ease this pain I like to avoid the problem entirely by not using them at all. However sometimes one has to cross talk between Java and Scala, and then one has to face the problem head on.

The cleanest approach that I have found, that does not result in a deranged mix of generics or implicits is to use an anti corruption layer as close to Java as possible that converts Java's use of null into an Option as soon as possible.

For example:
    Option(o).map(_.asInstanceOf[T])

If o is null, then the above snippet will evaluate to None, else Some(o).

String Option with map and closures is rarely readable, at least not until you have bathed in it for long enough to have Scala'ized your mind. So I like to wrap this up with a function, as follows.
  def asInstanceOfNbl[T]( o:AnyRef ) : Option[T] = Option(o).map(_.asInstanceOf[T])

No comments:

Post a Comment