For loop in scala without sequence? - Stack Overflow
Out of the loop for a couple of years, what's changed?
Strange Loop 2022 - Call for Presentations - Scala talks welcome!
We've had some great Scala talks over the years at Strange Loop (https://www.youtube.com/playlist?list=PLcGKfGEEONaBRUxzHaRF8MobumfYAXwwe) and would be happy to see some proposals. This year's conference is Sept 22-24 in St. Louis and speakers receive hotel, travel, and a stipend.
More on reddit.comFast C-style for loops in Scala 3
What is Scala programming language?
What is the future of Scala language?
What are loops in programming?
In fact, 0 to N does not actually populate anything with integers from 0 to N. It instead creates an instance of scala.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 Int in order to maintain the contract for the length method. 1 to Int.MaxValue works fine, as does 0 until Int.MaxValue. And the latter is what your while loop is doing anyway (to includes the right endpoint, until omits it).
Anyway, since the Scala for is a very different (much more generic) creature than the C for, the short answer is no, you can't do exactly the same thing. But you can probably do what you want with for (though maybe not as fast as you want, since there is some performance penalty).
Wow, some nice technical answers for a simple question (which is good!) But in case anyone is just looking for a simple answer:
//start from 0, stop at 9 inclusive
for (i <- 0 until 10){
println("Hi " + i)
}
//or start from 0, stop at 9 inclusive
for (i <- 0 to 9){
println("Hi " + i)
}
As Rex pointed out, "to" includes the right endpoint, "until" omits it.