Scala For Loops with Collections
A for loop can run once for each item in a collection. A collection is a value that holds a group of items together.
A loop visits each list item
The list holds three numbers, and length proves the count. The loop then prints each item in order.
@main def main(): Unit =
val numbers = List(4, 7, 9)
println(numbers.length)
for n <- numbers do
println(n)A guard skips small numbers
The guard keeps only rounds where the item is above 5. The numbers 2 and 5 never print.
@main def main(): Unit =
val numbers = List(2, 5, 8, 11)
for n <- numbers if n > 5 do
println(n)yield builds a new list
Each item is doubled, and yield collects the results. Printing the new list shows all three doubled values at once.
@main def main(): Unit =
val numbers = List(1, 2, 3)
val doubled = for n <- numbers yield n * 2
println(doubled)Example
@main def main(): Unit =
val scores = List(45, 80, 62, 90)
val passed = for s <- scores if s >= 50 yield s
println(passed)
for s <- scores if s >= 50 do
println(s)
println(scores.length)Key points
- List: a List holds items in order, written as List(1, 2, 3).
- Item at a time: the loop gives one item from the list in each round.
- Length: length gives the count of items in the list.
- Guard: a guard is an if after the generator that skips rounds where its condition is false.
- Yield: the word yield collects each round result into a new list.
- Original stays: a for-yield loop builds a new list and leaves the first list as it was.
In this example, the yield loop uses a guard to collect only the scores of 50 or more into a new list. The second loop prints those same scores one per line. The last line prints 4, the length of the first list.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Scastie
Exercise
What does this code print? val xs = List(3, 6), then val ys = for x <- xs yield x + 1, then println(ys).