Gradle基礎知識——Groovy的閉包

點擊圖片領取阿里云云產品幸運券

  • 定義閉包
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爲方法/函數

參考文獻


點擊圖片領取阿里云云產品幸運券

發佈了52 篇原創文章 · 獲贊 105 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章