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

Now that you’ve mastered higher order functions, you’ll learn about the type Option. Using null to represent nullable or missing values in Scala is an antipattern; 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’ll analyze the structure of the Option type. You’ll also discover how to create optional values and analyze them using pattern matching. 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?

Suppose you defined the following function to calculate the square root of an integer:

22.2 Creating an Option

22.3 Pattern matching on Option

Summary

Answers to quick checks