Scala downwards or decreasing for loop?

前端 未结 7 968
死守一世寂寞
死守一世寂寞 2020-12-13 01:56

In Scala, you often use an iterator to do a for loop in an increasing order like:

for(i <- 1 to 10){ code }

How would you d

相关标签:
7条回答
  • 2020-12-13 02:37

    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)
    }
    
    0 讨论(0)
提交回复
热议问题