开发者

How would I translate the following Java backward counting loop into Scala?

The following Java code is a very simple piece of code, but what are the equivalent constructs in Scala?

for (int i=10; i> 0; i-=2) {
   开发者_如何学C System.out.println(i);
}


The answer depends on whether you also need the code to be as fast as it was in Java.

If you just want it to work, you can use:

for (i <- 10 until 0 by -2) println(i);

(where until means omit the final entry and to means include the final entry, as if you used > or >=).

However, there will be some modest overhead for this; the for loop is a more general construct in Scala than in Java, and though it could be optimized in principle, in practice it hasn't yet (not in the core distribution through 2.9; the ScalaCL plugin will probably optimize it for you, however).

For a println, the printing will take much longer than the looping, so it's okay. But in a tight loop which you know is a performance bottleneck, you'll need to use while loops instead:

var i = 10
while (i > 0) {
  println(i)
  i -= 2
}


To iterate from 10 to 0 (exclusive) in steps of 2 in Scala, you can create a Range using the until and by methods and then iterate over them in a for loop:

for(i <- 10 until 0 by -2)


Of course you can do as well:

(0 to 4).map (10 - 2 * _)

or

List(10, 8, 6, 4, 2) foreach println

or how about

(2 to 10 by 2).reverse
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜