22   Option

After reading this lesson, you will be able to:

  • Represent a nullable value using Option
  • Use pattern matching on instances of the type Option

After mastering high order functions, you are going to learn about the type Option. In Scala, using null to represent nullable or missing values is an anti-pattern: use the type Option instead. The type Option ensures that you deal with both the presence or the absence of an element. Thanks to the Option type, you can make your system safer by avoiding nasty NullPointerExceptions at runtime. Your code will also be cleaner as you will no longer preventively check for null values: you will be able to clearly mark nullable values and act accordingly only when effectively needed. The concept of an optional type is not exclusive to Scala: if you are familiar with another language’s Option type, such as Java, you will recognize a few similarities between them. You are going to learn about the structure of the Option type. You are also going to learn how to create optional values and how to handle them using pattern matching on it. In the next lesson, you are going to see what are the most common operations that you perform with Option. In the capstone, you will use Option to represent that a winner for the game “Paper, Rock, Scissors, Lizard, Spock!” may be missing in case of a tie.

22.1   Why Option?

22.2   Creating an Option

22.3   Pattern Matching on Option

22.4   Summary

22.5   Answers to Quick Checks