2016-12-24 38 views
1

有没有办法将接口作为可变参数传递给groovy中的方法?如何将接口作为可变参数传递给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: [[email protected], [email protected]]

我需要做什么改变吗?

回答

5

Java风格的... -varargs仅仅是JVM的Handler[]。因此,为了使这项工作的捷径是:

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

(将它们作为一个演员阵容到Handler[]

+0

不错! Upvoted! :) – Opal

+0

@Opal只有一个处理程序通过,你的解决方案更短 - 所以返回的优惠;) – cfrick

+0

@cfrick这似乎很优雅。谢谢! – kshep92

3

这样:

interface Handler { 
    void handle(String) 
} 

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

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

你需要做的铸造。

+1

接受以前的答案,因为它看起来更优雅,但你的解决方案给我的代码辅助吧' '在IntelliJ中,所以有一个upvote。 – kshep92

相关问题