Groovy 方法调用后关闭

Groovy Closure after method call

A 已经在 Groovy 中研究了几个小时的闭包,但没有找到关于这种文件结构创建工作原理的解释。对我来说,它看起来就像方法调用后的一些闭包。我没有看到嵌套在调用树对象参数或 returns 的第一个方法中。

def tree = new FileTreeBuilder()
 tree.dir('src') {
    dir('main') {
       dir('groovy') {
          file('Foo.groovy', 'println "Hello"')
       }
    }

这是将 Closure 作为最后一个方法参数传递给 Groovy 的可能方法之一。

例如这个惯用的调用:

       dir('groovy') {
          //...
       }

也可以改写为(全是括号):

       dir('groovy', {
          //...
       } )

或as(完全没有括号):

       dir 'groovy', {
          //...
       }

它们都是可以互换的,可以根据上下文使用。

可以找到关于如何将闭包作为参数传递给方法的变体的解释Passing Closures To Methods,总结如下:

Closures are blocks of code we can assign to variables and pass around like objects. We can use closures as method arguments, but we must make sure we use the correct syntax. Groovy has some variations we can use to pass a closure into a method. If for example the closure is the last argument for a method we can put the closure outside the argument list.

您的问题是询问闭包如何出现在方法括号之外并且仍然按预期工作。将闭包作为参数传递给方法的一种变体是,如果闭包是方法调用中的最后一个参数。在那种情况下,闭包可以在括号(参数列表)之外:

work('Groovy') {
    assert it == 'Groovy'
}  // Last argument is closure and can be outside parenthesis.

所以在你的例子中:

def tree = new FileTreeBuilder()
 tree.dir('src') {
    dir('main') {
       dir('groovy') {
          file('Foo.groovy', 'println "Hello"')
       }
    }

调用 tree.dir('src'){...} 后跟一个闭包就是这种情况。闭包被视为方法调用 tree.dir() 的最后一个参数的值并匹配方法签名:File dir(String name, Closure cl)