Reputation: 3381
How do I increment the loop by 2 as equivalent to this in Java:
for (int i = 0; i < max; i+=2)
Right now in Scala I have:
for (a <- 0 to max)
For a fact max
will always be even. I don't know how to increment the counter to 2 in each loop.
Upvotes: 47
Views: 30872
Reputation: 461
This way you can use scala for loop like java one.
object Example extends App {
for(i <-0 to 20 by 2) {
println("Value of i = "+ i)
}
}
Output
Value of i = 0
Value of i = 2
Value of i = 4
Value of i = 6
Value of i = 8
Value of i = 10
Value of i = 12
Value of i = 14
Value of i = 16
Value of i = 18
Value of i = 20
Upvotes: 4
Reputation: 62835
Unsurprisingly easy:
scala> for (a <- 0 until 10 by 2) yield a
// Vector(0, 2, 4, 6, 8, 10)
Upvotes: 1
Reputation: 20285
Note the difference between to
and until
. With a strict i < max
you will want until.
val max = 10
scala> for(i <- 0 until max by 2)
| println(i)
0
2
4
6
8
scala> for(i <- 0 to max by 2)
| println(i)
0
2
4
6
8
10
Upvotes: 24