gpt4 book ai didi

使用一个或两个参数进行闭包的常规方法

转载 作者:行者123 更新时间:2023-12-04 00:06:51 25 4
gpt4 key购买 nike

我想编写一个将闭包作为参数并将两个参数传递给它的方法,但是编写该闭包的人可以根据自己的喜好指定一个或两个参数

我这样试过:

def method(Closure c){
def firstValue = 'a'
def secondValue = 'b'
c(firstValue, secondValue);
}

//execute
method { a ->
println "I just need $a"
}
method { a, b ->
println "I need both $a and $b"
}

如果我尝试执行此代码,结果是:
Caught: groovy.lang.MissingMethodException: No signature of method: clos2$_run_closure1.call() is applicable for argument types: (java.lang.String, java.lang.String) values: [a, b]
Possible solutions: any(), any(), dump(), dump(), doCall(java.lang.Object), any(groovy.lang.Closure)
at clos2.method(clos2.groovy:4)
at clos2.run(clos2.groovy:11)

我该怎么做?

最佳答案

您可以询问 maximumNumberOfParameters 调用它之前的闭包:

def method(Closure c){
def firstValue = 'a'
def secondValue = 'b'
if (c.maximumNumberOfParameters == 1)
c(firstValue)
else
c(firstValue, secondValue)
}

//execute
method { a ->
println "I just need $a"
}
method { a, b ->
println "I need both $a and $b"
}

输出:

I just need a
I need both a and b

关于使用一个或两个参数进行闭包的常规方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12077622/

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