【问题标题】:Why this closure call doesn't end up in a recursive call?为什么这个闭包调用不会以递归调用结束?
【发布时间】:2016-04-30 02:53:28
【问题描述】:

我是 Groovy 的新手,我正在研究官方文档中的闭包。 The 'delegate of a closure' topic 给出了下面的例子:

所以,在数字 5 中,我知道委托默认设置为所有者,在这种情况下是封闭闭包 enclosed

那么,为什么要打电话

{ -> delegate }.call()

enclosed 闭包内部不会以递归调用结束?对我来说看起来像是递归,但是如果您运行代码,则不是递归。我在这里缺少什么?

【问题讨论】:

    标签: recursion groovy closures


    【解决方案1】:
    def enclosed = {
        // delegate == owner == enclosed (variable)
        { ->
            // When this closure is called return the delegate (enclosed) 
            delegate 
        }.call() // Called immediately                          
    
        // above closure is same as writing
        // return delegate
    }
    
    // When enclosed in called the delegate is returned immediately
    // from the invocation of the inner closure, hence the result of the 
    // closure call is the closure (delegate) itself
    assert enclosed() == enclosed
    

    请记住,在enclosed 闭包中发生的任何事情都不会发生,直到调用enclosed()。 :) 它现在描绘了一幅清晰的画面吗?

    【讨论】:

    • 您能否在答案中加入@Emmanuel Rosa 在他的回答中所做的观察,即我们需要{ -> delegate }.call().call() 进行递归调用?我认为这对这个问题非常重要。谢谢!
    • 我同意,但我觉得这与最初提出的问题无关。问题是“我错过了什么?”。答案是理解闭包是如何工作的。毫无疑问 .call().call() 会导致递归,但整个代码块将毫无意义。此外,您如何确保(除了查看代码) .call() 返回一个 Closure ,您可以在此基础上再次调用 .call() 。最好先检查 .call() instanceof Closure 然后进行 .call()。如果我在这方面为您提供了帮助,我很高兴。
    【解决方案2】:

    enclosed 闭包中调用{ -> delegate }.call() 不会导致递归调用,因为call() 是在不同的闭包上调用的;在enclosed 中创建的那个。要获得递归调用,您可以这样做:{ -> delegate }.call().call()。第一个call() 返回enclosed,第二个调用它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-11-25
      • 2019-07-24
      • 2016-02-04
      • 2015-03-02
      • 1970-01-01
      • 1970-01-01
      • 2022-01-13
      相关资源
      最近更新 更多