Groovy筆記 二 閉包

2021-07-11 20:24:11 字數 1199 閱讀 9765

閉包應用模式:

1.策略模式:

def function (closure clo) 

}function

function

2.閉包引數:

def closure = 

closure new date(),"string"

3.模板方法模式:

class resouces 

def write() {}

def read() {}

def close() {}

def static use(resources r,closure clo) catch(ex) {} }}

def res = new resources()

resources.use }

resources.use }

4.閉包引數

closure.maximumnumberofparameters 表示引數個數

closure.parametertypes 表示閉包引數型別

5.閉包引數

owner:代表閉包的外層包如果沒有,就是閉包本身

this:永遠指向閉包最外層的類

delegate:閉包委託類

6.閉包呼叫

a.closure()

b.closure.call()

7.閉包在集合類中的應用

any(closure):判斷是否存在

every(closure):判斷是否每個都是

collect(closure):遍歷整個集合,通過closure裡面的演算法替換集合裡的元素

def result = [1,2,3,4].collect 

println result // [1,4,9,16]

8.閉包作為返回值

def multiply(x) 

}

Groovy閉包筆記

1.最後一行將會作為返回值 2.對於map型別,機引數列表中所有的map實參並組成map傳遞給第乙個形參。3.閉包可以設定預設值 4.it可以在有且僅有乙個未顯示宣告的引數時使用 5.閉包呼叫的標準寫法是 closurename.call 6.def定義的變數對 binding.variables....

隨筆 groovy閉包

class enclosing assert whatisthisobject this def whatisthis assert whatisthis this class enclosedininnerclass void run class nestedclosurescl assert n...

groovy閉包基本用法

閉包 基本用法 def closure my 呼叫閉包 closure my.call closure my 閉包能預設接收乙個引數 closure my hello closure 閉包接收多個引數 def closure1 closure1 1,2 閉包可以有預設值 再賦值 直接賦給j def ...