← Back to Scala Course | Chapter 4: Control Flow | Lesson 7 of 7

yield in for

In this page:

  1. yield in for

yield in for

Adding yield to a for comprehension, for (x <- collection) yield transform(x), transforms each element and collects the results into a new collection of the same type as the source, instead of just running side effects. This is functionally equivalent to calling .map (and with filters/multiple generators, roughly equivalent to .flatMap/.filter), but often reads more clearly for complex, multi-generator logic. The resulting collection's type matches the type being iterated over.

Note: for (x <- xs) yield f(x) is syntactic sugar that the compiler translates into a chain of map/flatMap/filter calls.

Example: yield in for

markup
object Main extends App {
  val numbers = 1 to 5

  val squares = for (n <- numbers) yield n * n
  println(squares)

  val evens = for (n <- numbers if n % 2 == 0) yield n
  println(evens)
}
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 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.