Farooque Farooque - 8 days ago 6
Scala Question

Undesired behavior of val in for loop in scala

I am executing below Scala code and it executes successfully without any compile time error and also gives the output given below:

val a = 0;
val numList = List(1,2,3,4,5,6);

// for loop execution with a collection
for( a <- numList ){
println( "Value of a: " + a );
}


output:

Value of a: 1
Value of a: 2
Value of a: 3
Value of a: 4
Value of a: 5
Value of a: 6


My question is if
a
is of type
val
then in
for
loop why the value of
a
gets change in each iteration of the loop and
a
accepts those changed values and prints?

Answer

The a used in the for loop is a different variable, which shadows the outer a.

One way to see that the two variables are different is to print the value of a after the loop. It still contains the initial value (0 in your case).

 val a = 0;
 val numList = List(1,2,3,4,5,6);

 // for loop execution with a collection
 for( a <- numList ){
     println( "Value of a: " + a );
 }

 println("After the loop, a = " + a)

Output:

Value of a: 1                                                                                                                                                                   
Value of a: 2                                                                                                                                                                   
Value of a: 3                                                                                                                                                                   
Value of a: 4                                                                                                                                                                   
Value of a: 5                                                                                                                                                                   
Value of a: 6
After the loop, a = 0

Note that the inner a is also a val (and not a var). At each iteration a new val named a is initialized with an element of numList.