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 ?
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
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With