Scala 2.10 will introduce a new class called Try for representing the results of computations that might fail. Try neatly encodes the concept of success and failure with a subclass for each concept: Success objects hold values and Failure objects hold exceptions.
Try is a nice little utility class. It isn’t terribly exciting, but it certainly comes in handy. Its simplicity reduces confusion, and error handling is an area where confusion is common.
Of course it is not necessary to explain to the enlightened reader the danger of using special values such as -1 or null to represent errors. Programmers are famous for misusing such values and crashing their programs (and rockets). Separating success and error results into two distinct types means the compiler can make sure they’re never mixed. A bit of type checking really can help to avoid problems.
Similar type-checking assistance was available in Scala 2.9 with Either. However Either is considerably more flexible and abstract than Try. Either can represent any two possibilities, not just success and failure. Either needs a little thought to understand, whereas Try needs almost none.
Try also provides useful methods for operating on return values.
- t.get – Get the result or throw an exception.
- t.getOrElse(x) – Get the result or a default value.
- t.isSuccess / t.isFailure – Check for success or failure.
- t.map / t.flatMap – Use in a for loop and never check for failures manually again!
Scala 2.10 is going to bring lots of great stuff and it will be easy to overlook Try. But Try is a valuable addition to any programmer’s toolkit.