Home > Articles > Programming

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

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.

  • + Share This
  • 🔖 Save To Your Account