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

Is it possible to pass a Groovy closure defined as a variable to a function for execution, with another variable as part of the passed call?

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

例如:

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

然后像这样传给另一个函数执行:

otherFunction(print("Jeff"))

如果其他函数有签名:

otherFunction(Closure clos):
    clos.call()

谢谢!

我已经弄清楚我哪里出错了,我需要我的函数 return 一个带有我的变量插值的闭包。

例如:

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

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

otherFunction(print("Jeff"))

回答了我自己的问题请关闭。

调用 otherFunction( print("Jeff") ) 的问题在于您将 print("Jeff") 的 return 值传递给它,该值为空,因为 println 不 return 任何东西(无效函数)。

取而代之的是,您必须传递闭包对象,该闭包对象是使用方法 call() 调用的。这是您自己想出来的,但我的方法更直接。其他解决方案是使用 function composition:

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()