是否可以将定义为变量的Groovy闭包传递给函数执行,并将另一个变量作为传递调用的一部分



正如标题所说,如果我定义了一个接受一个参数的闭包,我可以将它与一个要执行的参数一起传递吗。

例如:

def print = { String NAME -> println "$NAME"}

然后将其传递给另一个函数执行,如下所示:

otherFunction(print("Jeff"))

如果其他函数有签名:

otherFunction(Closure clos):
clos.call()

谢谢!

我已经找到了错误的地方,我需要我的函数返回一个带有插值变量的闭包。

例如:

def Closure print (String NAME){
{name -> println name}
}

然后调用以生成自定义闭包并传递:

otherFunction(print("Jeff"))

回答了我自己的问题,请结束。

调用otherFunction(print("Jeff">

相反,您必须传递用方法call((调用的layzy的闭包对象。这是你自己想出来的,但我的方法更直接。其他解决方案是使用函数组合:

def print = { println it }
def otherFunction(Closure clos) {
clos.call()
}
// this is equivalent with otherFunction(null)
//otherFunction( print("Jeff") )
// pass a closure object
otherFunction { print("Jeff") }
// using function composition
def printJeff = print << { "Jeff" }
printJeff()

最新更新