How to call functions from the vararg parameter?

Is it possible to call the functions that are contained in the vararg parameter?

def perform(functions:() => Unit*) = ?
+5
source share
2 answers

Yes, it’s very possible:

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

Remember that duplicate options are displayed as Seq[TheType]. In this case Seq[() => Unit], although this can be quite confusing, since it seems like it *should have a higher priority, but it is not.

Note that using parentheses gives the same type:

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

Happy coding.

+11
source

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

Let's say you find yourself with the following set of features:

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

If you try to do this in REPL

perform(fcts) // this does not compile

will not work.

, , , - Java ( , varargs -)

perform(fcts : _*) // works.

, Scala, List.

+2

All Articles