Scala flatMap example

The flatMap function is similar to map, but used a little differently.

First, lets make a couple arrays:

val x = List(1,2,3)
val y = List(4,5,6)

scala> List(x, y)
res38: List[List[Int]] = List(List(1, 2, 3), List(4, 5, 6))

scala> List(x, y).map( x => x )
res40: List[List[Int]] = List(List(1, 2, 3), List(4, 5, 6))

Sometimes it’s preferable to get a flattened list, that looks like this:

val z = List(1,2,3,4,5,6)

Which is what you do with flatMap:

scala> List(x, y).flatMap( x => x )
res41: List[Int] = List(1, 2, 3, 4, 5, 6)

An important thing to understand about flatMap is that anything that looks like an empty array will disappear, like so:

List(None, Some(1), None, Some(2)).flatMap(x => x)
res48: List[Int] = List(1, 2)

Note that this does not recurse, so you may want to call it twice:

List(
  List(None, Some(1)), 
  List(None, Some(2))
).flatMap(x => x)

List[Option[Int]] = 
  List(None, Some(1), None, Some(2))

Leave a Reply

Your email address will not be published. Required fields are marked *