Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a brief syntax for executing a block n times in Scala?

Tags:

scala

I find myself writing code like this when I want to repeat some execution n times:

for (i <- 1 to n) { doSomething() } 

I'm looking for a shorter syntax like this:

n.times(doSomething()) 

Does something like this exist in Scala already?

EDIT

I thought about using Range's foreach() method, but then the block needs to take a parameter which it never uses.

(1 to n).foreach(ignored => doSomething()) 
like image 561
Craig P. Motlin Avatar asked May 16 '10 03:05

Craig P. Motlin


1 Answers

You could easily define one using Pimp My Library pattern.

scala> implicit def intWithTimes(n: Int) = new {              |   def times(f: => Unit) = 1 to n foreach {_ => f}      | } intWithTimes: (n: Int)java.lang.Object{def times(f: => Unit): Unit}  scala> 5 times {      |   println("Hello World")      | } Hello World Hello World Hello World Hello World Hello World 
like image 133
missingfaktor Avatar answered Sep 20 '22 06:09

missingfaktor