Scala: Use Option instead of null to represent not set

In Java, null is commonly used to represent an Object value that is not-set:

While Java developers are forced to depend on method documentation to understand the semantics of null, Scala developers can instead code the semantics directly into the type system using Option:

This Scala snippet not only eliminates the need to explicitly declare the getter/setter but also removes the need to document nullability. From this declaration, it can be safely assumed that bar is never null and that bar may always be safely dereferenced. By using Option, users of the class are forced to deal with the possibility of bar being not set. In Java, documentation can easily be overlooked. The Java compiler will have no complaints about the following:

This snippet is problematic not just because it might dereference null, but because a NullPointerException doesn’t give the user, administrator or even later developers any indication of why the error has occurred. Only a later inspection of the source code and documentation of the getBar method would reveal that the null(not-set) value was not taken into account. If this code was buried in an edge case that is rarely or never exercised, the bug might not surface for years. Scala Option forces users of the Foo class to deal with the not-set state before accessing the value:

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">