Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala downwards or decreasing for loop?

scala> 10 to 1 by -1
res1: scala.collection.immutable.Range = Range(10, 9, 8, 7, 6, 5, 4, 3, 2, 1)

The answer from @Randall is good as gold, but for sake of completion I wanted to add a couple of variations:

scala> for (i <- (1 to 10).reverse) {code} //Will count in reverse.

scala> for (i <- 10 to(1,-1)) {code} //Same as with "by", just uglier.

Scala provides many ways to work on downwards in loop.

1st Solution: with "to" and "by"

//It will print 10 to 0. Here by -1 means it will decremented by -1.     
for(i <- 10 to 0 by -1){
    println(i)
}

2nd Solution: With "to" and "reverse"

for(i <- (0 to 10).reverse){
    println(i)
}

3rd Solution: with "to" only

//Here (0,-1) means the loop will execute till value 0 and decremented by -1.
for(i <- 10 to (0,-1)){
    println(i)
}

Having programmed in Pascal, I find this definition nice to use:

implicit class RichInt(val value: Int) extends AnyVal {
  def downto (n: Int) = value to n by -1
  def downtil (n: Int) = value until n by -1
}

Used this way:

for (i <- 10 downto 0) println(i)

You can use Range class:

val r1 = new Range(10, 0, -1)
for {
  i <- r1
} println(i)