gpt4 book ai didi

Groovy 闭包和带有函数参数的重载方法

转载 作者:行者123 更新时间:2023-12-04 19:32:47 26 4
gpt4 key购买 nike

我收到 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 常规):
    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。

最佳答案

您需要输入 as XXX在你的闭包之后给运行时一个你想去的地方的线索

    execute({ x -> println("Consumer") } as Consumer)
execute({ x, y -> println("BiConsumer") } as BiConsumer)

应该做

关于Groovy 闭包和带有函数参数的重载方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42696128/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com