Reputation: 10701
I encountered a strange error using for loops.
var verbose = true
for(i <- 0 to 1;
dummy = (if(verbose) println(s"i = $i") else ());
jrange = (if(i==0) 1 to 5 else 1 to 7).filter(_%2 == 0);
dummy2 = (if(verbose) println(s"jrange = $jrange") else ());
j <- jrange;
dummy3 = (if(verbose) println(s"j = $j") else ());
k <- List()
) println("looping")
Displays:
i = 0
jrange = Vector(2, 4)
i = 1
jrange = Vector(2, 4, 6)
j = 2
j = 4
j = 2
j = 4
j = 6
The thing which is weird is that the third println is never executed when i == 0 ! Do you know why?
Upvotes: 2
Views: 91
Reputation: 167891
It is executed, just not when you think it should be.
Why does this happen? Because the ranges are created first in a collection, and then that collection is used.
In particular, x = y
in a for loop gets translated into .map(x => (x,y))
, and Range
is not lazy in its evaluation of maps.
Upvotes: 3