什麼是閉包
一個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: