Appendix C. Options and boxes

 

If you have any experience with any other programming language, you’ll no doubt have seen code that does some guard-style operation, like this:

if (thing != null)
{
    thing.whatever();
}

The purpose is to prevent one from calling the whatever() method on someobject when it is null; otherwise the method would explode with a NullPointer-Exception at runtime because null is not a proper object instance. This style of programming can add a lot of noise to your code, and Scala has a solution for this: the Option type.

Scala abstracts the whole idea of a value being something or nothing, so rather than having to continually create guards within your code, you wrap your type with an Option and then, when you want to do something with that value, you pass the Option instance a function that’s only executed if the value is something.

Let’s illustrate that with an example:

scala> Option[String]("Tim").map(_.toLowerCase)
res1: Option[java.lang.String] = Some(tim)