Mikaël Mayer
Mikaël Mayer

Reputation: 10701

scala for loop strange

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

Answers (1)

Rex Kerr
Rex Kerr

Reputation: 167891

It is executed, just not when you think it should be.

  1. i = 0
  2. jrange = Vector(2, 4)
  3. i = 1
  4. jrange = Vector(2, 4, 6)
  5. j = 2
  6. j = 4
  7. j = 2
  8. j = 4
  9. j = 6

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

Related Questions