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

标签 groovy closures

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

我这样试过:

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/

相关文章:

ios - swift 中嵌套闭包内的位置引用的闭包参数

java - 在数据库中存储 BLOB 的最佳方式是什么?

groovy - 通过奴隶上的 jenkins post-groovy 脚本写入文件

域建模中的验证错误,Grails

intellij-idea - 如何在常规代码中列出 `cannot resolve symbol` 警告? (智能)

c# - 带有内部 Lambda 表达式的 Lambda 表达式

groovy - 在 groovysh 中如何声明和使用 Set 数据结构?

javascript - 闭包对象的继承和方法的重写

javascript - 为什么 setTimeout ("otherFunction()",2000) 错误?

JavaScript 闭包。为什么我的 "this"在这个方法中未定义