Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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) {
    System.out.println(i);
}
like image 933
deltanovember Avatar asked Jul 19 '11 02:07

deltanovember


3 Answers

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
}
like image 123
Rex Kerr Avatar answered Nov 18 '22 03:11

Rex Kerr


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)
like image 7
sepp2k Avatar answered Nov 18 '22 03:11

sepp2k


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
like image 5
user unknown Avatar answered Nov 18 '22 03:11

user unknown