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

for Comprehension Basics

A for comprehension is a for loop that can use several lists at once and skip items that do not fit. It is like matching every shirt with every pair of pants but only keeping the good outfits.

In this page:

  1. for Comprehension Basics
Syntax
scala
for {
  x <- collection1
  y <- collection2
  if condition
} {
  // body
}

for Comprehension Basics

A for comprehension can include multiple generators and filters, like for (x <- 1 to 3; y <- 1 to 3 if x != y) { ... }, iterating over combinations while filtering out unwanted ones inline.

This is more powerful than a basic single-generator loop and reads declaratively. Combined with yield (its own tutorial), for comprehensions become a way to build new collections rather than just run side effects.

Note: An if inside a for comprehension's generators filters elements inline, without needing a separate if statement in the body.

Example: for Comprehension Basics

markup
object Main extends App {
  for (x <- 1 to 3; y <- 1 to 3 if x != y) {
    println(s"($x, $y)")
  }
}
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. Adding a filter with if and forgetting that it applies to the generator before it, so pairs are skipped unexpectedly.
  2. Using a comma or wrong separator between generators, when they are separated by ; or new lines.
  3. Expecting nested output order to be y first, when the last generator (y) changes fastest.
🔒

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.