foreach: A Collection Method
In this lesson, you will be given a quick introduction to the foreach method.
We'll cover the following
Introduction
As this chapter deals with collections, it is important to know how to print the elements in a collection.
We cannot simply use println
or print
as they are used to print single values and collections are a collection of values. For this reason, Scala provides the foreach
method. This method can be used by every instance of every class in the collection library.
Syntax
The foreach
method is called on a collection of any type and takes a single argument. The argument must be a function/method that will be applied to each individual element of the collection.
For printing the elements of a collection, we would need to apply the println
or print
method to each element.
val collection = Seq(2,4,6,8,10)collection.foreach(println)
In the above code, we are calling foreach
on collection
and passing the println
method. When you press RUN, you will see all the elements of collection
printed on the console.
What is happening is that foreach
is traversing over collection
. It first goes to the first element of collection
, i.e., 2 and applies the println
method on it. This results in the printing of 2. foreach
then goes to the second element of collection
, i.e., 4 and performs the println
method on it. This results in the printing of 4. This continues until foreach
has traversed through all the elements of collection
.
In the next lesson, we will move on to the first collection: Arrays.