10.16. Combining map and flatten with flatMap
Problem
When you first come to Scala, the flatMap method can seem very foreign, so you’d
like to understand how to use it and see where it can be
applied.
Solution
Use flatMap in situations where
you run map followed by flatten. The specific situation is
this:
You’re using
map(or afor/yieldexpression) to create a new collection from an existing collection.The resulting collection is a list of lists.
You call
flattenimmediately aftermap(or afor/yieldexpression).
When you’re in this situation, you can use flatMap instead.
The next example shows how to use flatMap with
an Option. In this example, you’re told that you
should calculate the sum of the numbers in a list, with one catch: the
numbers are all strings, and some of them won’t convert properly to
integers. Here’s the list:
valbag=List("1","2","three","4","one hundred seventy five")
To solve the problem, you begin by creating a “string to integer”
conversion method that returns either Some[Int] or None, based on the String it’s given:
deftoInt(in:String):Option[Int]={try{Some(Integer.parseInt(in.trim))}catch{casee:Exception=>None}}
With this method in hand, the resulting solution is surprisingly simple:
scala> bag.flatMap(toInt).sum
res0: Int = 7Discussion
To see how this works, break the problem down into smaller steps.
First, here’s what happens when you use map on the initial collection of
strings:
scala> bag.map(toInt) res0: List[Option[Int]] = List(Some(1), ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access