So, while working my way through “Scala for the Impatient” I found myself wondering: Can you use a Scala for loop without a sequence?
For example, there is an exercise in the book that asks you to build a counter object that cannot be incremented past Integer.MAX_VALUE. In order to test my solution, I wrote the following code:
var c = new Counter
for( i <- 0 to Integer.MAX_VALUE ) c.increment()
This throws an error: sequences cannot contain more than Int.MaxValue elements.
It seems to me that means that Scala is first allocating and populating a sequence object, with the values 0 through Integer.MaxValue, and then doing a foreach loop on that sequence object.
I realize that I could do this instead:
var c = new Counter
while(c.value < Integer.MAX_VALUE ) c.increment()
But is there any way to do a traditional C-style for loop with the for statement?
In fact,
0 to Ndoes not actually populate anything with integers from0toN. It instead creates an instance ofscala.collection.immutable.Range, which applies its methods to all the integers generated on the fly.The error you ran into is only because you have to be able to fit the number of elements (whether they actually exist or not) into the positive part of an
Intin order to maintain the contract for thelengthmethod.1 to Int.MaxValueworks fine, as does0 until Int.MaxValue. And the latter is what your while loop is doing anyway (toincludes the right endpoint,untilomits it).Anyway, since the Scala
foris a very different (much more generic) creature than the Cfor, the short answer is no, you can’t do exactly the same thing. But you can probably do what you want withfor(though maybe not as fast as you want, since there is some performance penalty).