如何从vararg参数调用函数?

tra*_*ory 5 scala

是否可以调用vararg参数中包含的函数?

def perform(functions:() => Unit*) = ?
Run Code Online (Sandbox Code Playgroud)

小智 11

是的,非常可能:

>> def perform(functions:() => Unit*) = for (f <- functions) f()
>> perform(() => println("hi"), () => println("bye"))    
hi
bye
perform: (functions: () => Unit*)Unit
Run Code Online (Sandbox Code Playgroud)

请记住,重复的参数是公开的Seq[TheType].在这种情况下,Seq[() => Unit]虽然也可以是因为它有点混乱看起来*应该有更高的优先级,但事实并非如此.

请注意,使用括号产生相同的类型:

>> def perform(functions:(() => Unit)*) = for (f <- functions) f()
perform: (functions: () => Unit*)Unit
Run Code Online (Sandbox Code Playgroud)

快乐的编码.