Optio-null January 17, 2013
One of the first classes you will encounter in Scala is Option class which has 2 subclasses Some and None.
Represents optional values. Instances of Option are either an instance of Scala. Some or the object None
Basic use case of declaring and using pattern matching on options, notice the difference between Some(null) and Option(null):
Lets try toList on option values.
Since None is like the "empty list", you can use them to compose expressions over Options without having to worry about None, in the same way you dont have to worry about handling the empty list.
Option has support for map, flatMap and withFilter. We know that if we have these functions we can use the for expression.
Its worth looking at map, for, flatMap and foreach over option values. With the above in mind you can write more compact code on Some(x) which is the non empty list for Options. So if you use these functions over a None you always get None back, same as when you use them with List().
In the following example, note that flatMap followed by map removes the None from the list. If you consider that flatMap aggregates the resulting lists, since None is the same as the empty list, its natural that you don’t see them in the result.
Finally one more very nice trick I read recently from Scala in Depth for creating functions that handle values with optional arguments out of functions that take non optional parameters.