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

yield in for

Adding yield to a for loop makes it collect the results into a new list, like a machine that turns each toy into a painted toy and stacks them. Instead of just repeating, it produces something.

In this page:

  1. yield in for
Syntax
scala
val result = for (item <- collection) yield expression
val filtered = for (item <- collection if condition) yield expression

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)
}
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 for without yield and expecting a new collection, when it returns Unit and just runs the body.
  2. Putting side effects like println in the yield expression, when yield is meant for producing a value.
  3. Using yield on a Range and being surprised the result is a Vector rather than a List, since the result type follows the source collection.
Chapter Summary
  • if/else, while, do-while, and for loops control program flow.
  • for comprehensions and yield build results from loops.
  • Breaking out of a loop uses scala.util.control.Breaks.
🔒

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.