Is there a brief syntax for executing a block n times in Scala?

前端 未结 6 1567
误落风尘
误落风尘 2020-12-13 05:54

I find myself writing code like this when I want to repeat some execution n times:

for (i <- 1 to n) { doSomething() }

I\'m looking for

6条回答
  •  佛祖请我去吃肉
    2020-12-13 06:13

    It can be as simple as this:

    scala> def times(n:Int)( code: => Unit ) {
              for (i <- 1 to n) code
           }
    times: (n: Int)(code: => Unit)Unit
    
    scala> times(5) {println("here")}
    here
    here
    here
    here
    here
    

提交回复
热议问题