38    Either

After reading this lesson, you will be able to:

  • Define a value that can have one of two possible types, called Either
  • Decompose it using pattern matching
  • Transform its content using the map, and flatMap functions
  • Chain multiple instances of Either using for-comprehension

In the previous lesson, you have mastered the operations you can perform on a Map. In this lesson, you’ll discover a new Scala type called Either. You can use it to represent a value with one of two possible types. You’ll learn about its structure, and how to define an instance for it. You’ll use pattern matching to handle all its possible implementations. You’ll transform its values using the map and flatMap function, and you’ll chain multiple values using a for-comprehension statement. In the capstone, you will use the class Either to validate if your library can accept a given book request.

38.1       Why Either?

Imagine you want to write a function to validate a phone number. You do not want to throw exceptions because they are difficult to control and too risky, so you decide to use the type Option: you return the phone number wrapped in a Some if valid, None otherwise. It looks similar to the following:

38.2       Creating an Either

38.3       Pattern Matching on Either

38.4       The map and flatMap operations

38.5       For-comprehension

38.6       Summary

38.7       Answers to Quick Checks