I\'m looking for an equivalent of:
for(_ <- 1 to n)
some.code()
that would be shortest and most elegant. Isn\'t there in Scala anything si
You can create a helper method
def rep[A](n: Int)(f: => A) { if (n > 0) { f; rep(n-1)(f) } }
and use it:
rep(5) { println("hi") }
Based on @Jörgs comment I have written such a times-method:
class Rep(n: Int) {
def times[A](f: => A) { loop(f, n) }
private def loop[A](f: => A, n: Int) { if (n > 0) { f; loop(f, n-1) } }
}
implicit def int2Rep(i: Int): Rep = new Rep(i)
// use it with
10.times { println("hi") }
Based on @DanGordon comments, I have written such a times-method:
implicit class Rep(n: Int) {
def times[A](f: => A) { 1 to n foreach(_ => f) }
}
// use it with
10.times { println("hi") }