flatMap and for-comprehensions
In this page:
flatMap and for-comprehensions
flatMap(f) maps each element to a new collection (or Option) and then flattens all those results into a single collection, avoiding the nested collections a plain map would leave behind. This is essential when a transformation itself produces zero, one, or many results per input element. A for comprehension with yield is syntactic sugar that the compiler translates into a chain of map/flatMap/filter calls, which is why both approaches solve the same class of problems.
Note: A for comprehension with multiple <- generators is exactly equivalent to nested flatMap/map calls -- the compiler desugars it that way.
Example: flatMap and for-comprehensions
object Main extends App {
val words = List("hello", "world")
val letters = words.flatMap(w => w.toList)
println(letters)
val pairs = for {
x <- List(1, 2)
y <- List("a", "b")
} yield (x, y)
println(pairs)
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: