Lesson 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 a for-comprehension statement
- 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 statement, called “for-comprehension”. You are also going to see how you can integrate Boolean conditions in it to control further how the values are chained together. Finally, I’ll give you an overview of 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: