david.perez david.perez - 1 month ago 7
Scala Question

Combine varargs and argument by name

I'd like to be able to define a function like this:

def paralellize(func: ⇒ Unit *) = {
func.par.foreach(_.apply())
}


but it seems that Scala doesn't like it:

')' expected but identifier found.
def parallelize(func: => Unit *) = {
^
<console>:3: '=' expected but eof found.


I think this is due to the combination of varargs and by name arguments.

My intention is to be able to parallelize arbitrary code easily:

parallelize(
{
println("a")
Thread.sleep(1000)
println("A")
},
{
println("b")
Thread.sleep(1000)
println("B")
}
)

Answer

I'm not sure if i fully understood your question, but if you want pass many functions as argument you can try it like this

def paralellize(func: (() => Unit)* ) = {
  func.par.foreach(_.apply())
}