for Comprehension Basics
In this page:
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
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: