...

/

Iterate with for

Iterate with for

In this lesson, you will be introduced to the for expression.

Introduction

We sometimes come across scenarios where a block of code needs to be executed multiple times. The for expression is one such control structure that does just that. Scala’s for expression provides a wide variety of ways to express iterations depending on the object you want to iterate over; the simplest being a collection.

Control Flow

Let’s look at the general control flow of a for expression below.

The for loop iterates over values in a collection. The flow starts by checking if there are any elements in the collection we wish to iterate over. If elements do exist, take the first element and execute the block of code for the current element. Now iterate over all elements in the same manner until you reach the last element of the collection at which point you exit the ...