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 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 how 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 discovered the flatMap function and how you can use it to concatenate optional operations. Review the code from listing 23.8:

24.1.1 For-comprehension as syntactic sugar for nested map and flatMap calls

24.1.2 Filtering values within for-comprehension

24.2 Other operations on Option

Summary

Answers to quick checks