How to call a method n times in Scala?

后端 未结 5 1026
轮回少年
轮回少年 2021-02-18 23:04

I have a case where I want to call a method n times, where n is an Int. Is there a good way to do this in a \"functional\" way in Scala?

case class Event(name: S         


        
5条回答
  •  心在旅途
    2021-02-18 23:53

    With recursion:

    def repeat(n: Int)(f: => Unit) { 
      if (n > 0) {
        f
        repeat(n-1)(f)
      }
    }
    
    repeat(event.quantity) { queue.enqueue(event.value) }
    

提交回复
热议问题