In this chapter, we have seen how we can model the possibility of an optional value with Option
and the possibility of an error with Either
. We demonstrated how these types can replace exceptions while guaranteeing referential transparency.
We also saw how we can combine several Option
or Either
types using flatMap
. This works well when we have to check for optional values or errors sequentially—call function1
; if there is no error, call function2
; if there is no error, call function3
. If any of these functions return an error, we return that error and stop the call chain, as shown in the following code:
def sequentialErrorHandling(x: String): Either[MyError, String] = for { a <- function1(x) b <- function2(a) c <- function3(b) } yield c
However, in some situations, we would want to call several functions in parallel and return all the errors that might have occurred. For instance, when you enter some personal details to purchase a product from an...