Scala Fold and Foreach
Foreach and fold are list methods that work through every item in a list. Foreach runs an action on each item, and fold combines all the items into one value.
Foreach with println
Passing println to foreach prints every item in the list. Each name lands on its own line, in list order.
@main def main(): Unit =
val names = List("Ana", "Ben", "Cid")
names.foreach(println)Foreach with a lambda that prints
Here foreach receives a lambda that prints its item times ten. The action can do any work with each item, not just print it as it is.
@main def main(): Unit =
val nums = List(2, 3, 4)
nums.foreach(x => println(x * 10))Fold builds a total step by step
fold starts at 0 and adds each item into the running total, one at a time. For the first list the total grows 0, 1, 3, 6, and finally 10.
@main def main(): Unit =
val nums = List(1, 2, 3, 4)
println(nums.fold(0)(_ + _))
println(List(10, 20, 30).fold(0)(_ + _))Example
@main def main(): Unit =
val nums = List(2, 3, 4)
println(nums.fold(1)(_ * _))
println(nums.fold(0)(_ + _))
nums.foreach(println)Key points
- Foreach: The foreach method runs an action once for every item in the list, in order.
- Foreach result: Foreach gives back Unit, because its job is the action itself, not a new value.
- Fold: The fold method combines all items into a single value, starting from a start value and folding each item in, one at a time.
- Start value: The value in the first parentheses of fold is where the combining begins.
- Combining step: The second parentheses of fold hold the step that joins the running total with the next item.
In this example, the first fold starts at 1 and multiplies each item in, so 1 times 2 times 3 times 4 gives 24. The second fold starts at 0 and adds each item, giving 9. Foreach then prints each number on its own line, in list order.
Note
The sum method is a ready-made fold that starts at zero and adds, so fold(0)(_ + _) and sum agree.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Scastie
Exercise
What does List(2, 3, 5).fold(1)(_ * _) give back?