如何将接口作为varargs参数传递给Groovy中的方法?

如何将接口作为varargs参数传递给Groovy中的方法?,groovy,variadic-functions,Groovy,Variadic Functions,在groovy中有没有办法将接口作为varargs参数传递给方法 以下是我想做的: interface Handler { void handle(String) } def foo(Handler... handlers) { handlers.each { it.handle('Hello!') } } foo({ print(it) }, { print(it.toUpperCase()) }) 当我运行以下代码时,会出现错误: 没有方法的签名:ConsoleScr

在groovy中有没有办法将接口作为varargs参数传递给方法

以下是我想做的:

interface Handler {
    void handle(String)
}

def foo(Handler... handlers) {
    handlers.each { it.handle('Hello!') }
}

foo({ print(it) }, { print(it.toUpperCase()) })
当我运行以下代码时,会出现错误:

没有方法的签名:ConsoleScript8.foo()适用于参数类型:(ConsoleScript8$\u run\u closure1,ConsoleScript8$\u run\u closure2)值:[ConsoleScript8$\u run_closure1@4359df7,ConsoleScript8$\u运行_closure2@4288c46b]

我需要更改什么?

这样:

interface Handler {
   void handle(String)
}

def foo(Handler... handlers) {
   handlers.each { it.handle('Hello!') }
}

foo({ print(it) } as Handler, { print(it.toUpperCase()) } as 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)

您需要执行强制转换。

Java样式
..
-varargs只是JVM的
处理程序[]
。因此,实现这一目标的最短方法是:

foo([{ print(it) }, { print(it.toUpperCase()) }] as Handler[])

(将它们作为列表转换传递给
处理程序[]

Java样式
..
-varargs只是
处理程序[]
传递给JVM。因此,实现这一目标的最短方法是:

foo([{ print(it) }, { print(it.toUpperCase()) }] as Handler[])

(将它们作为列表强制转换传递给
处理程序[]

@Opal只要传递一个处理程序,您的解决方案就更短了-因此返回了优惠;)@这看起来很优雅。谢谢大家!@Opal只传递了一个处理程序,您的解决方案更短-因此返回了优惠;)@这看起来很优雅。非常感谢。接受上一个答案是因为它看起来更优雅,但您的解决方案为我提供了IntelliJ中
it
的代码帮助,所以请进行向上投票。接受上一个答案是因为它看起来更优雅,但您的解决方案为我提供了IntelliJ中
it
的代码帮助,所以请进行向上投票。