- 定義閉包
def closure_name = {
// closure body
}
上面代碼定義一個名爲 closure_name 的閉包,用途由 closure body 中的代碼定義。匿名閉包指不聲明閉包變量名,只有閉包方法體{ //closure body }
- 無參閉包
def closure_with_no_param = {
println 'hello,world!'
}
執行closure_with_no_param()
或者closure_with_no_param.call()
,將輸出hello,world!
- 含參閉包
def closure_with_param = {
x,y-> println "x plus y is " + (x+y)
}
執行closure_with_param(1,2)
,結果爲x plus y is 3!
可以設置默認參數值,例如:
def closure_with_param = {
x,y=0-> println "x plus y is " + (x+y)
}
執行closure_with_param(1)
,結果爲x plus y is 1!
- 與方法/函數的結合使用
定義閉包
def closure_demo = {
x -> println x
}
定義方法
def method_name(Closure closure_name){
for(int i=0;i<=100;i+=1){
closure_name(i)
}
}
執行method_name(closure_demo)
或者method_name closure_demo
,結果輸出如下:
1
2
3
...
100
- Gradle構建腳本簡析
dependencies {
compile group: 'commons-collections', name: 'commons-collections', version: '3.2'
testCompile group: 'junit', name: 'junit', version: '4.+'
}
其中:
dependencies
爲方法或函數名,參數爲閉包類型- 接下來的
{...}
是一個閉包
//這是個閉包
{
compile group: 'commons-collections', name: 'commons-collections', version: '3.2'
testCompile group: 'junit', name: 'junit', version: '4.+'
}
group: 'commons-collections'
將group
變量的值設爲commons-collections
compile
爲方法/函數
參考文獻
- https://www.w3cschool.cn/groovy/groovy_closures.html
- http://blog.csdn.net/cckevincyh/article/details/75212415