23 Working with Option: map and flatMap
After reading this lesson, you will be able to:
- Transform an element contained in an Option using map
- Simplify a nested optional structure using flatten
- Chain optional values together using flatMap
In the previous lesson, you have discovered the type Option and how to pattern match on it. After working with optional types for some time, you will realize that some of its operations are particularly recurrent: Option offers you a set of high order functions for them so that you can be more productive and you do not have to use pattern matching every time. In this lesson, I’ll introduce you to some of the most common and useful predefined functions on Option. You are going to learn how to transform an optional value using map. You’ll see how to simplify a nested optional structure using flatten. Finally, you are going to learn how to combine optional values in an order sequence using flatMap. These functions describe patterns that are common to many Scala types other than Option: understanding them is crucial as you are going to encounter them in many different contexts. In the capstone, you will use the functions map on Option to extract data from the winner (if any) of the game “Paper, Rock, Scissors, Lizard, Spock!”.