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

flatMap and for-comprehensions

flatMap changes each item into a small list and then flattens all of them into one, like unpacking small boxes into one big tray. It is the key to chaining steps that each produce results.
Syntax
scala
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.

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)
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Using map when the function returns a collection, ending up with a nested List[List[Char]] instead of the flat result from flatMap.
  2. Passing a function to flatMap that returns a single value rather than a collection or Option, which gives a type error.
  3. Mixing collection types in a for comprehension, such as a List and an Option, and getting a confusing type error.
Chapter Summary
  • Higher-order functions take or return functions, including map, filter, and reduce.
  • Anonymous functions, closures, currying, and partial application create flexible functions.
  • Function composition and flatMap with for-comprehensions combine operations.
🔒

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.