While certainly not a recommended practice in Java, null is occasionally used to represent the failure of a simple operation:
1 2 3 4 |
class Foo { // may return null to indicate failure! public Integer readInt() { ... } } |
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:
1 2 3 4 |
class Foo { // None indicates failure! def readInt() : Option[Int] = { ... } } |
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:
1 2 3 |
class Foo { def readInt() : Either[Exception, Int] = { ... } } |
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.