Scala: Use Option or Either to replace null as a failure indicator

While certainly not a recommended practice in Java, null is occasionally used to represent the failure of a simple operation:

Java developers must depend on documentation to explain if null is a possible return value, and if it is, what the meaning of null is. In this case, null is used to indicate the operation of readInt failed. Scala developers have a couple of options here:

In this Scala snippet, it is explicit that the function may not return a value. However, it is still not clear that None indicates failure and this should still be documented. Generally, I like to have as much information as possible about failures. This final Scala snippet uses Either to remove any ambiguity:

In this snippet, no documentation is required since it is explicit that this function either returns an Exception or a value. Callers of this function are forced to deal with the possible failure of the operation before accessing the return value. If the operation did fail, callers are provided with a possibly informative Exception to explain the failure.

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="">