Search code examples
scalaloopscompiler-theoryfor-comprehension

Scala "<-" for comprehension


I have found that Scala always has a "natural explanation" to anything. Always something like "ohh, but that's just a function being called on this and that object with this and that parameter". In a sense, nothing is really compiler-magic as we know it from other languages.

My question is on the <- operator as used in the following code:

for(i <- 0 to 10) println(i)

In this example I can see it being rewritten to something like:

0.to(10).foreach((i:Int)=>println(i))

but this doesn't explain how the i got carried into the anonymous function inside the foreach function. At the point where you write i it is not an object, and not yet a declared variable. So what is it, and how is it being carried over to the inside of foreach?

My guess is that I finally discovered something which is in fact compiler magic

Thanks for your time.

To clarify, my question is: how does the <- operator work in the 1st line of code since i is not an object on which it can be called as a function.


Solution

  • <- is a language-defined keyword symbol, as is => but in distinct contrast to -> (which is a defined symbol). Because it is part of the basic Scala grammar, it can be used to create bindings (for the i in your example) which is something that cannot be done by user-defined constructs.