当我尝试使用包含带有功能参数的重载方法的代码时,我得到Ambiguous error
。
我写了一个小片段,显示了一个模棱两可的行为:
import java.util.function.BiConsumer
import java.util.function.Consumer
class Test {
static void main(String... args) {
execute({ x -> println("Consumer") })
execute({ x, y -> println("BiConsumer") })
}
static void execute(Consumer<Integer> c) {
c.accept(100)
}
static void execute(BiConsumer<Integer, Integer> c) {
c.accept(1, 2)
}
}
输出(2.4.9 groovy):
Exception in thread "main" groovy.lang.GroovyRuntimeException: Ambiguous method overloading for method Test#execute.
Cannot resolve which method to invoke for [class Test$_main_closure1] due to overlapping prototypes between:
[interface java.util.function.BiConsumer]
[interface java.util.function.Consumer]
at groovy.lang.MetaClassImpl.chooseMostSpecificParams(MetaClassImpl.java:3268)
at groovy.lang.MetaClassImpl.chooseMethodInternal(MetaClassImpl.java:3221)
at groovy.lang.MetaClassImpl.chooseMethod(MetaClassImpl.java:3164)
at groovy.lang.MetaClassImpl.pickStaticMethod(MetaClassImpl.java:1516)
at groovy.lang.MetaClassImpl.retrieveStaticMethod(MetaClassImpl.java:1412)
at org.codehaus.groovy.vmplugin.v7.Selector$MethodSelector.chooseMeta(Selector.java:553)
at org.codehaus.groovy.vmplugin.v7.Selector$MethodSelector.setCallSiteTarget(Selector.java:954)
at org.codehaus.groovy.vmplugin.v7.IndyInterface.selectMethod(IndyInterface.java:228)
at Test.main(Test.groovy:7)
但它适用于java-lambdas,我不明白在这种情况下如何使用groovy-closures。
答案 0 :(得分:4)
您需要在关闭后放置as XXX
,以便为运行时提供您想要去的线索
execute({ x -> println("Consumer") } as Consumer)
execute({ x, y -> println("BiConsumer") } as BiConsumer)
应该这样做
答案 1 :(得分:0)
也许使用Closure:
execute(Closure <Integer> c) {
c (10)
}
execute (Closure <Integer, Integer> c) {
c (10, 30)
}