Monday, 18 June 2012


Even newcomers to Scala know about Option class. We are starting from it as from solution to Nullpointer errors, later we finding it as a very useful Monad implementation. It is dual natured - one is Monadic Container - value is inside - and second is Monadic Zero with no value. Actually sometimes it is useful to have some value even in Zero container. For example non breaking error handing. Errors are important and even can be accumulated into the List.


There is an embedded into language solution for above issue: scala.Either. "Represents a value of one of two possible types (a disjoint union.) Instances of Either are either an instance of Left or Right."
The difference to Option is simple: both implementations (Left and Right)  incapsulates a value. Conventions for this is: Right is for result and Left contains error. Here is example taken from the official documentation (reworked to show Error Handling):

1. Pattern Matching : 2. Additionally to pattern matching value can be tested via isLeft or is Right methods. 3. Fold: 4. A projection: 5. For-comprehension (via flatMap):

No comments:

Post a Comment