The flatMap method

Before we formally define the rules, let's have a brief discussion about flatMap. We assume that you are familiar with Scala collections and are aware of the existence of the flatten method. So, just the name of flatMap tells us that it maps and then flattens, as shown here:

def flatMap[T](f: Y => Monad[T]) : Monad[T] = flatten(map(f))

We don't have the monad definition we referred to in the preceding code yet, but that's fine. We will get there. For now, let's just look at it as another generic parameter. You should also know that flatten has the following declaration:

def flatten[T](x: F[F[T]]): M[T]

For example, if F is actually a List, flatten will convert a list of lists into a simple list of whatever the type of the ...

Get Scala Design Patterns - Second Edition 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.