I learn Scala for some time and can\'t clearly understand the usage of Option. It helps me to avoid null checks when I chain functions (according to docs). That\'s clear for
While Option can makes your class definition look verbose, the alternative is to not know when you need to test whether a variable is defined. I think that in your example, if your class were immutable (all the fields were vals), you would not need so many Options.
For your method foo, if you return null, you need to document it and the client needs to read that documentation. Then the client will write a bunch of code like:
val result = foo(x)
if (result != null) {
println(result)
}
If instead you define foo to return an Option[Result], the type system forces the client to handle the possibility of an undefined result. They also have the full power of the collections classes.
result foreach println
An additional advantage of using the collections method with an Option instead of testing for null is that if your method is extended to a multi-element collection (such as a List), you might not need to change your code at all. For example, you might initially assume your Racer can only have a single crew, so you define val crew: Option[Crew] and you might test if the crew is older than 30 with crew.forall(_.age > 30).getOrElse(false). Now if you changed the definition to val crew: List[Crew] your old code would still compile and now you would check if all of your crew members are over 30.
Sometimes you need to deal with null because libraries you are using may return it. For example, when you get a resource, you might get a null result. Fortunately, it is easy to defensively wrap results so they are transformed into an option.
val resource = Option(this.getClass.getResource("foo"))
If getResource returned null then resource equals None, and otherwise it is a Some[URL]. Cool!
Unfortunately, Option is likely to have some overhead because it involves an extra object creation. However, that overhead is minimal compared to a null pointer exception!