What a Scala for loop is
A Scala for loop doesn't have the three-part header of C or Java. It takes each value of a collection in turn, and for counting the collection is a range:
for (item <- range) {
// instructions that run once per value
}
The pieces are:
itemis the loop variable. On each pass it holds the next value of the range.<-reads as "taken from". The part to its right is called a generator.rangedecides which values are visited, and therefore how many times the body runs.
You never declare the loop variable with var and never update it yourself. It is a fresh val on each pass, so assigning to it inside the body is a compile error.
Ranges with until
The expression 0 until 4 builds a range that starts at 0 and stops before 4. Its values are 0, 1, 2 and 3:
for (i <- 0 until 4) {
println("Hello world!")
}
This prints Hello world! four times. The variable i is not used in the body, which is fine. Here it only makes the body run once for each value.
Because until excludes its end, 0 until n has exactly n values, which is why it is the usual way to repeat something n times. The related word to includes its end: 0 to 4 has five values, 0 through 4. Mixing the two up is the most common off-by-one error with Scala ranges.
What happens on each pass
For 0 until 4 the loop works like this:
iis 0. The body runs.iis 1. The body runs.iis 2. The body runs.iis 3. The body runs.- The range has no more values, so the loop ends.
There is no condition to check and no counter to increase by hand, so a range-based loop can't become an infinite loop through a forgotten update.
The assignment: print a sentence 5 times
The task is to print "I promise to learn coding." five times.
- Write the loop header. Use
for (i <- 0 until 5). The range has five values, 0 to 4, so the body will run five times. - Print the message inside the body with
println. The body runs once per value, so oneprintlnline produces five lines of output.
for (i <- 0 until 5) {
println("I promise to learn coding.")
}
The output is the sentence on five separate lines.
Common mistakes
- Using
toinstead ofuntil.0 to 5has six values and prints the message six times. - Writing
=instead of<-. The generator needs the arrow.for (i = 0 until 5)doesn't compile. - Trying to change the loop variable. A line such as
i += 1inside the body is rejected, becauseican't be reassigned. To change the step, change the range. - Writing
i++. Scala has no++operator, and the range already moves forward for you.
Key takeaways
for (x <- range)runs its body once for each value of the range.a until bstops beforeb;a to bincludesb.- The loop variable is created by the loop and can't be reassigned.
0 until nrepeats a block exactlyntimes.
