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

前端 未结 6 1563
误落风尘
误落风尘 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:31

    I'm not aware of anything in the library. You can define a utility implicit conversion and class that you can import as needed.

    class TimesRepeat(n:Int) {
      def timesRepeat(block: => Unit): Unit = (1 to n) foreach { i => block }
    }
    object TimesRepeat {
      implicit def toTimesRepeat(n:Int) = new TimesRepeat(n)
    }
    
    import TimesRepeat._
    
    3.timesRepeat(println("foo"))
    

    Rahul just posted a similar answer while I was writing this...

提交回复
热议问题