Start learning free

LESSON 109 OF 348 · FOR LOOPS - LOOPING OVER ARRAYS

For Loop - Execution Flow in Scala in Scala

Lesson

Scala uses the brackets ({}) to indicate which lines of code are part of a for loop and which are not.

Take this code for example:

val languages = Array("Python", "Java", "Scala")

for (language <- languages) {
  println("I love " + language)
  println("I want to get better at it")
}

Both println statements are part of the loop since they are written inside the brackets.

This means that both messages will be printed for every language in the languages list. The output of that code would be:

I love Python
I want to get better at it
I love Java
I want to get better at it
I love Scala
I want to get better at it

As for this code:

val languages = Array("Python", "Java", "Scala")

for (language <- languages) {
  println("I love " + language)
}
println("I want to get better at them")

The println("I want to get better at them") is not part of the loop.

This means that only println("I love " + language) will be executed for every language in the languages list.

Then, when the for loop is over, the println("I want to get better at them") will be executed only once.

The output of this program would be:

I love Python
I love Java
I love Scala
I want to get better at them

Execution flow

Lastly, note that the execution of a program always begins on the first line. The code is then executed one line at a time from top to bottom. This is known as execution flow and is the order a program in Scala executes code.

For example, this program:

val fruits = Array("banana", "apple", "kiwi")

println("I'm hungry!")

for (fruit <- fruits) {
  println("I'm gonna eat:")
  println(fruit)
}
  

println("I love my life!")

prints:

I'm hungry!
I'm gonna eat:
banana
I'm gonna eat:
apple
I'm gonna eat:
kiwi
I love my life!


Assignment:

Add a for loop inside our code in the editor such that the final program would print:

Today we'll learn about:
Python
Java
Scala
Let's code!
STEP 1 OF 1
    Ctrl + Enter to check

    Exercise Create A For Loop in Scala

    Keep going with ScalaAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free