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

for Comprehension Basics

In this page:

  1. for Comprehension Basics

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

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.