- 2.1 Conditional Expressions
- 2.2 Statement Termination
- 2.3 Block Expressions and Assignments
- 2.4 Input and Output
- 2.5 Loops
- 2.6 Advanced for Loops and for Comprehensions
- 2.7 Functions
- 2.8 Default and Named Arguments L1
- 2.9 Variable Arguments L1
- 2.10 Procedures
- 2.11 Lazy Values L1
- 2.12 Exceptions
- Exercises
2.5 Loops
Scala has the same while and do loops as Java and C++. For example,
while (n > 0) { r = r * n n -= 1 }
Scala has no direct analog of the for (initialize; test; update) loop. If you need such a loop, you have two choices. You can use a while loop. Or, you can use a for statement like this:
for (i <- 1 to n) r = r * i
You saw the to method of the RichInt class in Chapter 1. The call 1 to n returns a Range of the numbers from 1 to n (inclusive).
The construct
for (i <- expr)
makes the variable i traverse all values of the expression to the right of the <-. Exactly how that traversal works depends on the type of the expression. For a Scala collection, such as a Range, the loop makes i assume each value in turn.
When traversing a string or array, you often need a range from 0 to n – 1. In that case, use the until method instead of the to method. It returns a range that doesn’t include the upper bound.
val s = "Hello" var sum = 0 for (i <- 0 until s.length) // Last value for i is s.length - 1 sum += s(i)
In this example, there is actually no need to use indexes. You can directly loop over the characters:
var sum = 0 for (ch <- "Hello") sum += ch
In Scala, loops are not used as often as in other languages. As you will see in Chapter 12, you can often process the values in a sequence by applying a function to all of them, which can be done with a single method call.