8

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);
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
deltanovember
  • 42,611
  • 64
  • 162
  • 244
  • 2
    There is no direct equivalent in Scala. See *Cruel.scala* attached to http://scala-programming-language.1934581.n4.nabble.com/optimizing-simple-fors-tp2545502p2546347.html for an approximation. May be Rex can post it here too as an answer. – huynhjl Jul 19 '11 at 03:12

3 Answers3

24

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
}
Rex Kerr
  • 166,841
  • 26
  • 322
  • 407
  • instead of while-loops tail-recursive methods are preferred in a functional language like Scala. – kiritsuku Jul 20 '11 at 11:03
  • @Antoras - Tail-recursive methods are less clear and syntactically clunkier for simple indexed iteration: `var i=0; while (i – Rex Kerr Jul 20 '11 at 15:30
  • Ok, that is true. Recursion makes more sense when the method returns a value: `def x(i: Int, v: SomeValue): SomeValue = if (i == 10) v else x(i+1, NewValue)` – kiritsuku Jul 20 '11 at 21:19
  • `def sum(a: Array[Int]) = { var i,s = 0; while (i= a.length) s else sum(a, i+1, s+a(i))` still looks like a win for iteration to me. – Rex Kerr Jul 21 '11 at 02:12
7

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)
sepp2k
  • 363,768
  • 54
  • 674
  • 675
  • `to` is a member of RichInt (http://www.scala-lang.org/api/current/index.html#scala.runtime.RichInt) which creates a Range.Inclusive (http://www.scala-lang.org/api/current/scala/collection/immutable/Range$$Inclusive.html), where `by` is defined; it creates another `Inclusive` `i` is implicitly converted to a RichInt to enable this process to start – Dylan Jul 19 '11 at 03:25
5

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
user unknown
  • 35,537
  • 11
  • 75
  • 121