How to call a method n times in Scala?

Jonas picture Jonas · Sep 23, 2011 · Viewed 15.2k times · Source

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: String, quantity: Int, value: Option[BigDecimal])

// a list of events
val lst = List(
    Event("supply", 3, Some(new java.math.BigDecimal("39.00"))),
    Event("sale", 1, None),
    Event("supply", 1, Some(new java.math.BigDecimal("41.00")))
    )

// a mutable queue
val queue = new scala.collection.mutable.Queue[BigDecimal]

lst.map { event =>
    event.name match {
        case "supply" => // call queue.enqueue(event.value) event.quantity times
        case "sale" =>   // call queue.dequeue() event.quantity times
    }
}

I think a closure is a good solution for this, but I can't get it working. I have also tried with a for-loop, but it's not a beautiful functional solution.

Answer

tenshi picture tenshi · Sep 23, 2011

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()