【问题标题】:Groovy closures - not understandable call orderGroovy 闭包 - 无法理解的调用顺序
【发布时间】:2016-02-22 13:28:09
【问题描述】:

我尝试构建一个小型 DSL,但是我不明白下面的执行顺序。

DSL 有一个声明为summarize tests of 'me'

我的 Groovy 解释脚本是:

def tests = {
    [of: { who ->
            println "IN CLOSURE"
            "HALLO" // dummy value for testing
        }]
}

def summarize(Closure c) {
    println "SUMMARIZE - CALL CLOSURE"
    def f = c()
    println "SUMMARIZE - CALL CLOSURE"
    println "RESULT $f"
    f
}

我的调用脚本有

def g = summarize tests of 'me'
println g

输出是

SUMMARIZE - CALL CLOSURE
SUMMARIZE - CALL CLOSURE
RESULT [of:com.github.groovyclient.TestRailClient$_closure1$_closure13@470f1802]
IN CLOSURE
HALLO

我实际上想在 summarize 方法中已经有 tests 闭包的结果,但似乎还没有调用内部闭包 - 在那之后发生了什么魔术,所以脚本确实有结果正确吗?

谁能解释一下,为什么是执行顺序?我怎样才能在summarize 方法中检索HALLO

感谢您的帮助

【问题讨论】:

    标签: groovy closures


    【解决方案1】:

    在您的示例中,test 是一个返回地图的闭包。 如果你打电话给test(),你会得到[of: {...}]

    这是您在打印f 时在控制台中看到的内容。 对于 groovy

    summarize tests of 'me'
    

    等价于

    summarize(tests).of('me')
    

    你的summarize(tests) 执行tests(),返回映射[of:{..}]。之后,您将执行返回关闭的map.of,然后使用参数me 调用此关闭。

    有不同的选项来获得你想要的东西,但这取决于你想要实现的完整的“dsl”,而不仅仅是这个特殊的用例。我认为只有这句话最简单的方法是返回一个中间对象,当你调用 `of' 时会触发它:

    def summarize(t) {
      return [
        of: { who ->
          def f = t().of(who)
          println f
        }
      ]
    }
    

    【讨论】:

    • 感谢您的澄清 - 那么是否有任何方法来构建它,以便在 summarize 中已经提供关闭的结果?
    • 我已经添加了一个可以做什么的例子,但老实说,它很难看。你应该更准确地定义你想要的 DSL ;-)
    • 再次感谢 - 这个想法是过滤/映射结果。 tests of 'me' 是一个闭包,它返回一组结果(完整的对象信息)。 Summarize 然后例如只返回结果的标题。
    • summarize test.of('me')然后,如果你想调用test.of并将结果传递给summarize
    猜你喜欢
    • 2014-10-08
    • 2011-01-02
    • 2016-01-30
    • 1970-01-01
    • 1970-01-01
    • 2015-07-26
    • 1970-01-01
    • 1970-01-01
    • 2017-10-01
    相关资源
    最近更新 更多