Ad space (banner)
Lesson 6 / 20

Repeating (the for expression)

This lesson covers looping in Scala with a for expression.

You repeat with for (variable <- range). Using a range such as 1 to 5 is the typical form.

The sample code writes for (i <- 1 to 5) to print the numbers 1 through 5 in order.

A common early stumble is the difference between to (last number included) and until (last number excluded). 1 to 5 means 1–5 and 1 until 5 means 1–4, so check that you have the range you intended.

In professional work, for expressions are used to process every element of a list, but higher-order functions such as map — covered in a later lesson — are just as common.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Scala directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)