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 f(x: Int) = if (x % 2 == 0) Some(x) else None f: (x: Int)Option[Int]
The result of evaluating the function is Option
, as shown in the following code. However, we wish to do something about this. Let's say, we add...