Groovy   发布时间:2022-04-12  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了Groovy闭包和带有功能参数的重载方法大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
当我尝试使用包含带有功能参数的重载方法代码时,我收到了不明确的错误.

我写了一个小片段,显示一个模棱两可的行为:

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.

解决方法

您需要在关闭后放置XXX,以便为运行时提供您想要去的线索

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

应该这样做

大佬总结

以上是大佬教程为你收集整理的Groovy闭包和带有功能参数的重载方法全部内容,希望文章能够帮你解决Groovy闭包和带有功能参数的重载方法所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。