How to call a method n times in Scala?

后端 未结 5 1013
轮回少年
轮回少年 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:28

    The simplest solution is to use range, I think:

    (1 to n) foreach (x => /* do something */)
    

    But you can also create this small helper function:

    implicit def intTimes(i: Int) = new {
        def times(fn: => Unit) = (1 to i) foreach (x => fn)
    }
    
    10 times println("hello")
    

    this code will print "hello" 10 times. Implicit conversion intTimes makes method times available on all ints. So in your case it should look like this:

    event.quantity times queue.enqueue(event.value) 
    event.quantity times queue.dequeue() 
    

提交回复
热议问题