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

前端 未结 6 1560
误落风尘
误落风尘 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条回答
  •  萌比男神i
    2020-12-13 06:38

    You could easily define one using Pimp My Library pattern.

    scala> implicit def intWithTimes(n: Int) = new {        
         |   def times(f: => Unit) = 1 to n foreach {_ => f}
         | }
    intWithTimes: (n: Int)java.lang.Object{def times(f: => Unit): Unit}
    
    scala> 5 times {
         |   println("Hello World")
         | }
    Hello World
    Hello World
    Hello World
    Hello World
    Hello World
    

提交回复
热议问题