Start learning free

LESSON 111 OF 414 · FOR LOOPS - LOOPING OVER ARRAYS

Looping Through Arrays in Scala: The for Loop

Lesson Read the full explanation

A for loop is a special type of loop in Scala which allows us to loop over the items of a collection, such as an array.


Looping through an array:

For example, an array is a sequence of items, so we can use a for loop to iterate over each item and do something with it:

val fruits = Array("banana", "orange", "pear", "kiwi")

for (fruit <- fruits) {
  println("I eat " + fruit)
}

The output of this code is:

I eat banana
I eat orange
I eat pear
I eat kiwi

Let's break down this code:

  • The for keyword that indicates the start of a for loop.
  • fruit is the loop variable. It will take the value of each different item in the collection
  • The <- separates the loop variable from the collection we will iterate on
  • fruits is the collection to loop over

Assignment
Now let's greet our friends using a for loop!


Hint
Look at the examples above if you get stuck.


STEP 1 OF 2
    Ctrl + Enter to check

    SCALA · FOR LOOPS - LOOPING OVER ARRAYS

    Looping Through Arrays in Scala, explained

    The for loop

    A for loop runs a block of code once for each item in a collection such as an array. You don't manage indices yourself: Scala hands you each item in turn.

    val fruits = Array("banana", "orange", "pear", "kiwi")
    
    for (fruit <- fruits) {
      println("I eat " + fruit)
    }
    

    The output is one line per fruit:

    I eat banana
    I eat orange
    I eat pear
    I eat kiwi
    

    Reading the syntax

    • for starts the loop.
    • fruit is the loop variable. On each pass it holds the current item. You choose its name, and it exists only inside the loop. You don't declare it with val.
    • <- is the generator arrow. Read it as "in": the whole header says "for each fruit in fruits".
    • fruits is the collection to walk through, in order from the first element to the last.
    • The part in braces is the body, which runs once per item.

    An array with four elements runs the body four times. An empty array runs it zero times, and nothing is printed.

    The exercise: greeting friends

    The starting code has an array of names:

    val friends = Array("Andy", "Mary", "John")
    
    1. Write the loop header. The lesson asks for a loop variable named friend over the friends array: for (friend <- friends). The singular name for the item and the plural name for the collection make the header read naturally.
    2. Print the greeting inside the body. The message is Hey, Andy! with each name in turn. An s string inserts the variable: in s"Hey, $friend!" the $friend is replaced by the current name.
    val friends = Array("Andy", "Mary", "John")
    
    for (friend <- friends) {
        println(s"Hey, $friend!")
    }
    

    The output is:

    Hey, Andy!
    Hey, Mary!
    Hey, John!
    

    Details worth knowing

    • Interpolation needs the s. Without it, "Hey, $friend!" is printed literally, dollar sign included.
    • The punctuation after the name is safe. In $friend!, the ! can't be part of a name, so the interpolation stops there. If the next character could belong to a name, use braces: ${friend}s.
    • The array is not changed. The loop only reads each item. Assigning to friend inside the body is not allowed, because the loop variable can't be reassigned.
    • Other collections work the same way. List, Vector, ArrayBuffer and Set can all go to the right of <-.

    Loops with indices and ranges

    When you also need the position of each item, loop over the indices, or pair each item with its index using zipWithIndex:

    for (i <- friends.indices) {
      println(i + ": " + friends(i))
    }
    
    for ((friend, i) <- friends.zipWithIndex) {
      println(s"$i $friend")
    }
    

    The first loop prints 0: Andy, 1: Mary and 2: John. The second prints 0 Andy, 1 Mary and 2 John. Ranges also work as collections: 1 to 3 includes 3 and counts 1, 2, 3, while 1 until 3 stops before 3 and counts 1, 2. Looping with 0 to friends.size would include the invalid index 3, so loop with until or indices when you use indices.

    Common mistakes

    • Writing in or : instead of <-. Scala's generator is the arrow.
    • Using a name that doesn't match. If the header says friend, the body must say friend, not friends. Using the array name inside the body prints the array object, not one name.
    • Looking for a loop counter. There is none unless you ask for indices.

    Key takeaways

    • for (item <- collection) { ... } runs the body once for each item, in order.
    • The loop variable takes each value in turn and is only visible inside the loop.
    • Use an s string to put the loop variable into the printed message.
    • Use indices, zipWithIndex or until when positions matter.
    Keep going with ScalaAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free