在Scala中循环的增量为2

在Scala中循环的增量为2,scala,for-loop,Scala,For Loop,在Java中,如何将循环增加2,与此等效: for (int i = 0; i < max; i+=2) for(int i=0;ifor(a (0 until max by 2) foreach {...} 就足够了。通过这种方式,您可以将scala用于类似java one的循环。 object Example extends App { for(i <-0 to 20 by 2) { println("Value of i = "+ i) }

在Java中,如何将循环增加2,与此等效:

for (int i = 0; i < max; i+=2)
for(int i=0;i
现在在Scala,我有:

for (a <- 0 to max)

for(aTry
for(a注意
to
till
之间的区别。对于严格的
i
,您将希望直到

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
val max=10
scala>for(i)for(i

scala> for (a <- 0 until 10 by 2) yield a
// Vector(0, 2, 4, 6, 8, 10)
(a
scala>for(a

(0 until max by 2)  foreach {...}

就足够了。

通过这种方式,您可以将scala用于类似java one的循环。

object Example extends App {
    for(i <-0 to 20 by 2) {
        println("Value of i = "+ i)
    }
}

使用
to
将包括
max
,这不是问题所要求的。
object Example extends App {
    for(i <-0 to 20 by 2) {
        println("Value of i = "+ i)
    }
}
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