concept flatten in category scala

appears as: flatten
Get Programming with Scala

This is an excerpt from Manning's book Get Programming with Scala.

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 higher 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!”.

You can use the flatten function to combine two nested optional values as follows:

Listing 23.4: Example usage of flatten on Option
def ownerDrivingLicense(car: Car): Option[String] =
  car.owner.map(_.drivingLicense).flatten

The function flatten acts on an instance of Option[Option[A]], and it returns an Option[A]: