O'Reilly logo

Scala Functional Programming Patterns by Atul S. Khot

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

FlatMap

The flatMap method takes a function as a parameter, applies it to each element in a container, and flattens the overall result as shown in the following code:

scala> val f1 = (n: Int) => (1 to n).toList map { _ % 2 == 0 }
f1: Int => List[Boolean] = <function1>
scala> :t f1
Int => List[Boolean]
scala> List(2,3) flatMap f1
res4: List[Boolean] = List(false, true, false, true, false)

As earlier, f1 is of the type X => List[Y], where X is bound to Int and Y is bound to Boolean. Applying flatMap to List(2,3), which is List[Int], we get List[Boolean]. So, given the function, X => List[Y] we were able to get a transformation, List[Int] => List[Boolean].

Where does this come in useful? To know this, let's look at the following example:

scala> def ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required