score:89

Accepted answer
1 to n foreach { _ => some.code() }

score:10

I would suggest something like this:

List.fill(10)(println("hi"))

There are other ways, e.g.:

(1 to 10).foreach(_ => println("hi"))

Thanks to Daniel S. for the correction.

score:10

With scalaz 6:

scala> import scalaz._; import Scalaz._; import effects._;
import scalaz._
import Scalaz._
import effects._

scala> 5 times "foo"
res0: java.lang.String = foofoofoofoofoo

scala> 5 times List(1,2)
res1: List[Int] = List(1, 2, 1, 2, 1, 2, 1, 2, 1, 2)

scala> 5 times 10
res2: Int = 50

scala> 5 times ((x: Int) => x + 1).endo
res3: scalaz.Endo[Int] = <function1>

scala> res3(10)
res4: Int = 15

scala> 5 times putStrLn("Hello, World!")
res5: scalaz.effects.IO[Unit] = scalaz.effects.IO$$anon$2@36659c23

scala> res5.unsafePerformIO
Hello, World!
Hello, World!
Hello, World!
Hello, World!
Hello, World!

[ Snippet copied from here. ]

score:20

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") }

Related Query

More Query from same tag