什么是闭包
一个groovy闭包就像一个代码块或者方法指针,他是定义而后执行的一段代码,可是他有一些特性:隐含变量,支持自由变量,支持currying 。java
咱们先来看看一些例子:闭包
1 |
def clos = { println "hello!" } |
3 |
println "Executing the Closure:" |
在上面的例子中”hello!”是由于调用clos()函数才打印出来的,而不是在定义的时候打印出来的。ide
参数
闭包的参数在->以前列出,好比:函数
1 |
def printSum = { a, b -> print a+b } |
若是闭包的参数是少于2个的话,那么 ->是能够省略的。ui
Parameter notes
A Closure without -> , i.e. {} , is a Closure with one argument that is implicitly named as ‘it’. (see below for details) In some cases, you need to construct a Closure with zero arguments, e.g. using GString for templating, defining EMC Property etc. You have to explicity define your Closure as { -> } instead of just { }this
You can also use varargs as parameters, refer to the Formal Guide for details. A JavaScript-style dynamic args could be simulated, refer to the Informal Guide.spa
自由变量
闭包能引用在参数列表中没有列出的变量,这些变量成为自由变量,他们的做用范围在他们定义的范围内:指针
2 |
def incByConst = { num -> num + myConst } |
另一个例子:code
2 |
def localVariable = new java.util.Date() |
3 |
return { println localVariable } |
6 |
def clos = localMethod() |
8 |
println "Executing the Closure:" |
隐式变量
it
若是你有一个闭包可是只有一个参数,那么你能够省略这个参数,好比:orm
1 |
def clos = { print it } |
this, owner, and delegate
this : 和java中是同样的, this
refers to the instance of the enclosing class where a Closure is defined
owner : the enclosing object (this
or a surrounding Closure)
delegate : by default the same as owner
, but changeable for example in a builder or ExpandoMetaClass
3 |
println this. class .name |
4 |
println delegate. class .name |
6 |
println owner. class .name |
12 |
def clos = new Class1().closure |
闭包做为方法参数
当一个方法使用闭包做为最后一个参数的话,那么就能够内嵌一个闭包,好比:
1 |
def list = [ 'a' , 'b' , 'c' , 'd' ] |
4 |
list. collect ( newList ) { |
在上面的collect方法中,他接受一个一个List和闭包,上面的代码等价于下面的代码:
1 |
def list = [ 'a' , 'b' , 'c' , 'd' ] |
4 |
def clos = { it.toUpperCase() } |
5 |
list. collect ( newList, clos ) |
7 |
assert newList == [ "A" , "B" , "C" , "D" ] |
更多的信息:
Groovy继承了 java.lang.Object
而且许多的 Collection
和Map
的许多方法都接受闭包做为参数的 See GDK Extensions to Object for practical uses of Groovy's Closures.
See Also: