在Groovy方法调用中使用括号

时间:2016-09-06 09:21:56

标签: groovy

我开始学习Groovy,并且理解括号在方法调用中是可选的,所以

   def list = [0, 1, 2, 3]
   list.each ({ item ->
     println "Item: $item"
   })

相同
   def list = [0, 1, 2, 3]
   list.each { item ->
     println "Item: $item"
   }

但现在找到了这个例子

   def list = [0, 1, 2, 3]
   list.each() { item ->
     println "Item: $item"
   }

也有效。如何首先用空参数列表调用方法,然后在它之后指定闭包?

1 个答案:

答案 0 :(得分:2)

当涉及到关闭时,情况会有所不同。闭包有一个特殊的工具,作为最后一个参数(as explained here)。

作为另一个例子,请考虑:

class Foo {
    int bar(s, c) {
        return c(s)
    }

    int abc(c, s) {
        return c(s)
    }
}

def foo = new Foo()
def s = "fox"

这是一种经典风格:

assert 3 == foo.bar(s, { it.size() })

然而,这将作为最后一个论点用于闭包:

assert 3 == foo.bar(s) { it.size() }

这很经典:

assert 3 == foo.abc({ it.size() }, s)

但这不起作用

// assert 3 == foo.abc({ it.size() }) s

毫无疑问,推理是如果只有一个参数,就像List.each()一样,那么语法非常优雅:

list.each { item -> println item }