【问题标题】: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?是否可以将定义为变量的 Groovy 闭包传递给函数以供执行,而另一个变量作为传递调用的一部分?
【发布时间】:2020-12-22 16:38:58
【问题描述】:

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

例如:

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

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

otherFunction(print("Jeff"))

如果其他函数有签名:

otherFunction(Closure clos):
    clos.call()

谢谢!

【问题讨论】:

    标签: groovy closures higher-order-functions


    【解决方案1】:

    我已经知道我哪里出错了,我需要我的函数返回一个带有内插变量的闭包。

    例如:

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

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

    otherFunction(print("Jeff"))
    

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

    【讨论】:

    • SO 鼓励添加(也接受)您自己的答案。无需关闭。
    【解决方案2】:

    调用 otherFunction(print("Jeff")) 的问题是你将 print("Jeff") 的返回值传递给它,因为 println 不返回任何东西(void 函数),所以它是 null。

    你必须传递闭包对象,这个闭包对象是用方法 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()
    

    【讨论】:

    • 谢谢你的解释,我想我会用你的方法重写我的解决方案。已接受答案。
    猜你喜欢
    • 1970-01-01
    • 2015-07-16
    • 2014-04-02
    • 1970-01-01
    • 2011-11-03
    • 2017-08-22
    • 1970-01-01
    • 2015-09-28
    • 1970-01-01
    相关资源
    最近更新 更多