Analytics

Wednesday, January 30, 2013

Scala Options

One of the most interesting and unfamiliar features of Scala for Java programmers is the Option. The easiest way to think about it is as an explicit representation of an object that may be null. For example, let's say you have a method getString() which returns a String that may be null. In Java you would do:

while in Scala you would do:

where we are leveraging pattern matching. The Option() apply method takes an object and turns it into either a Some (which is generic on the type) or a None depending on whether the object is null. So by using Options you are enforcing an actual type distinction between null and non-null instances of the object. This might not seem like a big deal, but if done thoroughly, you could end up with code in which you are guaranteed that an object not wrapped by an option is non-null. That means you could get rid of NullPointerExceptions! Anyone who has programmed long enough in Java knows how much of a win that would be. Unfortunately, because Scala projects typically have to integrate with a lot of existing Java code, we can't quite reach that ideal state. But if you're diligent in wrapping the return values of third-party libraries in options when the result may be null, you can enforce this checking in your own code.

Besides compile-time distinction between null and non-null instances, options are designed in such a way that they play very nicely with the functional side of Scala. In fact, options are treated as a collection where there is either zero or one element. That means you can do all sorts of interesting things such as:

In each of these cases you would have to do an annoying null check before doing what you actually wanted to do. Scala's functional constructs for operating on collections provide concise ways of handling options without you ever having to mention null or None.

2 comments:

  1. type-safe nullables ftw. Maybe in Haskell blew my mind

    ReplyDelete
  2. Haha yeah. Whoever thought that segfaults and NPEs weren't the only way to program?

    ReplyDelete