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:
Syntax
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
object Main extends App {
for (x <- 1 to 3; y <- 1 to 3 if x != y) {
println(s"($x, $y)")
}
}
Login to try C/C++/Java/PHP code in the editor
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
- Adding a filter with
ifand forgetting that it applies to the generator before it, so pairs are skipped unexpectedly. - Using a comma or wrong separator between generators, when they are separated by
;or new lines. - Expecting nested output order to be
yfirst, when the last generator (y) changes fastest.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: