When I wrote the Scala Cookbook, I gave each recipe and then each chapter my full attention. I thought that if I wrote each recipe as well as possible, and included important recipes in each chapter, well, I wanted each chapter to be worth the price of the entire book. That was my goal.
As a result of this effort -- and perhaps to the chagrin of my editor -- the Scala collections chapters ended up being 130 pages in length.
This is an excerpt from the Scala Cookbook (partially modified for the internet). This is Recipe 10.16, “How to Combine map and flatten with flatMap”
When you first come to Scala from an object-oriented programming background, the
flatMap method can seem very foreign, so you’d like to understand how to use it and see where it can be applied.
flatMap in situations where you run
map followed by
flatten. The specific situation is this:
This is an excerpt from the Scala Cookbook (partially modified for the internet). This is Recipe 10.15, “How to Flatten a List of Lists in Scala with
You have a list of lists (a sequence of sequences) and want to create one list (sequence) from them.
flatten method to convert a list of lists into a single list. To demonstrate this, first create a list of lists:
Scala flatMap FAQ: Can you share some Scala flatMap examples?
Sure. When I was first trying to learn Scala, and cram the collections' flatMap method into my brain, I scoured books and the internet for great flatMap examples. Once I had a little grasp of it I started creating my own examples, and tried to keep them simple.
Using flatMap on a list of Strings
The following examples show the differences between
flatMap on a sequence of String: