What is flatMap?

flatMap is a method on collections that, at a surface level, transforms each element into another collection of any type, then takes all the elements out of those collections and puts them into one. It is like a map followed by a flatten.

Why do two things in one step?

Conceptually, List.map is always 1:1 – each element in the input collection produces one element for the output collection. With flatMap, each element in the input collection produces 0 or more elements for the output collection.

This is like the map in CouchDB’s MapReduce: the map function can emit zero or more output documents for each input.

Or as @Deech says, “It’s just a monadic bind.” In slightly more colloquial terms, we can think of it as: pass a functor into a context, and get back the same kind of context with different stuff in it.