Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is the 'i' variable being incremented in this loop?

Tags:

scala

Below code prints 0,1,2,3,4,5,6,7,8,9

for (i <- 0 until 10) {
    println(i) 

How is the var 'i' being incremented ? I suspect there is something implicit occurring but inspecting the signature of 'until' which returns a Range I dont know what this is ?

like image 670
blue-sky Avatar asked Nov 30 '22 04:11

blue-sky


1 Answers

for in scala is not a loop, but something called a comprehension. In your case it simply calls Range.foreach, because 0 until 10 creates a Range. It then just recursively calls the function you pass to the foreach for each value in the range.

edit:

Depending on how exactly your for looks, it will create nested calls to map, flatMap, foreach, filter...

E.g:

for {
  x <- 0 until 10
  y <- 0 until 10
} yield x * y

Will be compiled to

(0 until 10) flatMap { x =>
  (0 until 10) map { y =>
    x*y
  }
}

and

for {
  x <- 0 until 10
  if x % 2 == 0
} yield x * 2

will be compiled to something like

(0 until 10).filter { x =>
  x % 2 == 0
}.map { x =>
  x * 2
}
like image 82
drexin Avatar answered Dec 21 '22 22:12

drexin