开发者

How to call functions from a vararg-parameter?

开发者 https://www.devze.com 2023-03-13 11:04 出处:网络
Is it possi开发者_Python百科ble to call functions which are contained in a vararg-parameter? def perform(functions:() => Unit*) = ?

Is it possi开发者_Python百科ble to call functions which are contained in a vararg-parameter?

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


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.


@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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号