david.perez
david.perez

Reputation: 7022

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

Upvotes: 0

Views: 331

Answers (2)

david.perez
david.perez

Reputation: 7022

A shorter variation of Kamil answer:

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

Upvotes: 0

Kamil Banaszczyk
Kamil Banaszczyk

Reputation: 1153

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

Upvotes: 4

Related Questions