flatMap and for-comprehensions
In this page:
val result = collection.flatMap(x => other_collection(x))
val same = for {
x <- collection
y <- other_collection(x)
} yield y
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.
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
- Using
mapwhen the function returns a collection, ending up with a nestedList[List[Char]]instead of the flat result fromflatMap. - Passing a function to
flatMapthat returns a single value rather than a collection orOption, which gives a type error. - Mixing collection types in a
forcomprehension, such as aListand anOption, and getting a confusing type error.
- Higher-order functions take or return functions, including
map,filter, andreduce. - Anonymous functions, closures, currying, and partial application create flexible functions.
- Function composition and
flatMapwith for-comprehensions combine operations.
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: