是否有一种方法可以将接口作为varargs参数传递到groovy中的方法?
这是我想做的:
interface Handler {
void handle(String)
}
def foo(Handler... handlers) {
handlers.each { it.handle('Hello!') }
}
foo({ print(it) }, { print(it.toUpperCase()) })
运行以下代码时,我会收到错误:
No signature of method: ConsoleScript8.foo() is applicable for argument types: (ConsoleScript8$_run_closure1, ConsoleScript8$_run_closure2) values: [ConsoleScript8$_run_closure1@4359df7, ConsoleScript8$_run_closure2@4288c46b]
我需要更改?
Java风格的...
-Varargs仅对JVM Handler[]
。因此,最短的方法是:
foo([{ print(it) }, { print(it.toUpperCase()) }] as Handler[])
(将它们作为列表将其传递给Handler[]
)
这样:
interface Handler {
void handle(String)
}
def foo(Handler... handlers) {
handlers.each { it.handle('Hello!') }
}
foo({ print(it) } as Handler, { print(it.toUpperCase()) } as Handler)
您需要进行铸造。