trajectory
trajectory

Reputation: 1509

How to call functions from a vararg-parameter?

Is it possible to call functions which are contained in a vararg-parameter?

def perform(functions:() => Unit*) = ?

Upvotes: 5

Views: 172

Answers (2)

Mirco Dotta
Mirco Dotta

Reputation: 1300

@pst gave you the answer, I'm just adding another bit for future reference.

Let's say you find yourself with the following collection of functions:

val fcts = List(() => println("I hate"), () => println("this"))

If you try to execute this in the REPL

perform(fcts) // this does not compile

won't work.

However you can tell the compiler that what you are really trying to achieve is to pass the list as a Java array (this is how varargs are represented in the bytecode)

perform(fcts : _*) // works.

Clearly, this hold for any Scala collection, not just List.

Upvotes: 2

user166390
user166390

Reputation:

Yes, very possible:

>> def perform(functions:() => Unit*) = for (f <- functions) f()
>> perform(() => println("hi"), () => println("bye"))    
hi
bye
perform: (functions: () => Unit*)Unit

Remember that repeated parameters are exposed as Seq[TheType]. In this case, Seq[() => Unit], although it can be sort of confusing as it looks like the * should have higher precedence, but it does not.

Note that using parenthesis yields the same type:

>> def perform(functions:(() => Unit)*) = for (f <- functions) f()
perform: (functions: () => Unit*)Unit

Happy coding.

Upvotes: 11

Related Questions