← Back to Scala Course | Chapter 9: Functional Programming | Lesson 8 of 8

flatMap and for-comprehensions

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

markup
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)
}
🔒

Chapter Quiz — Complete all 8 topics to unlock

0/8 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.