23 Working with Option: map and flatMap

 

After reading this lesson, you will be able to

  • Transform an element contained in an Option using the map operation
  • Simplify a nested optional structure using flatten
  • Chain optional values together using flatMap

In the previous lesson, you 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. The class Option offers you a set of higher order functions for them to be more productive, and you do not have to use pattern matching every time. This lesson will introduce you to some of the most common and useful predefined functions on Option. You’ll discover how to transform an optional value using map. You’ll see how to simplify a nested optional structure using flatten. Finally, you’ll learn how to combine optional values in an order sequence using flatMap. These functions describe patterns common to many Scala types other than Option: understanding them is crucial as you’ll 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!”

23.1 Transforming an Option

23.1.1 The map function

23.1.2 The flatten function

23.1.3 The flatMap function

Summary

Answers to quick checks