Introducing the flatMap function

Another example of a function that encapsulates a pattern of functional programming is flatMap. Imagine we need to create a function that computes the following mathematical expression: (2 / x) / y + 3. Let's try to do this with the division function that we defined previously:

def f2Match(x: Double, y: Double): Try[Double] =  divide(2, x) match {    case Success(r1) => divide(r1, y) match {      case Success(r2) => Success(r2 + 3)      case f@Failure(_) => f    }    case f@Failure(_) => f  }

The code becomes spaghetti-like here. First, we analyze the result of dividing 2 by x. If successful, we would divide it by y. Then we analyze the result of that division, and if there was no error, we add 3 to the result.

Here, we can no ...

Get Mastering Functional Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.