24 Working with Option: for-comprehension
After reading this lesson, you will be able to:
- Chain optional values together using for-comprehension.
- Introduce conditions within for-comprehension constructs
- Code using the most common operations defined on Option
In the previous lesson, you have learned how to use the functions map, flatten, and flatMap to manipulate optional values. In this lesson, you are also going to discover a more readable and elegant way of combining instances of Option thanks to a new type of construct, called “for-comprehension”. You’ll also see how to integrate Boolean conditions to control further how the values are chained together. Finally, you’ll discover other useful operations implemented for Option, such as isDefined, getOrElse, find, and exists. In the capstone, you will use the function getOrElse on Option to provide an alternative message for your HTTP request when a draw of the game “Paper, Rock, Scissors, Lizard, Spock!” occurs.
24.1 For-comprehension on Option
In the previous lesson, you have discovered the flatMap function and how you can use it to concatenate optional operation together. Let’s have a look at the code in listing 23.8: