10.9. Looping over a Collection with foreach
Problem
You want to iterate over the elements in a collection with the
foreach
method.
Solution
The foreach
method takes a
function as an argument. The function you define should take an element
as an input parameter, and should not return anything. The input
parameter type should match the type stored in the collection. As
foreach
executes, it passes one
element at a time from the collection to your function until it reaches
the last element in the collection.
The foreach
method applies your
function to each element of the collection, but it doesn’t return a
value. Because it doesn’t return anything, it’s said that it’s used for
its “side effect.”
As an example, a common use of foreach
is to output information:
scala>val x = Vector(1, 2, 3)
x: scala.collection.immutable.Vector[Int] = Vector(1, 2, 3) scala>x.foreach((i: Int) => println(i))
1 2 3
That’s the longhand way of writing that code. For most
expressions, Scala can infer the type, so specifying i: Int
isn’t necessary:
args
.
foreach
(
i
=>
println
(
i
))
You can further shorten this expression by using the ubiquitous underscore wildcard character instead of using a temporary variable:
args
.
foreach
(
println
(
_
))
In a situation like this, where a function literal consists of one statement that takes a single argument, it can be condensed to this form:
args
.
foreach
(
println
)
For a simple case like this, the syntax in the last example is typically used.
Discussion
As long as your function (or method) takes ...
Get Scala Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.