隨筆 groovy閉包

2021-10-01 09:45:23 字數 3168 閱讀 5370

|||

class

enclosing

assert

whatisthisobject()

==this

def whatisthis =

assert

whatisthis()

==this}}

class

enclosedininnerclass

}void

run()}

class

nestedclosurescl(

)}assert

nestedclosures()

==this

}}

class

enclosing

assert

whatisownermethod()

==this

def whatisowner =

assert

whatisowner()

==this}}

class

enclosedininnerclass

}void

run()}

class

nestedclosurescl(

)}assert

nestedclosures()

== nestedclosures

}}

class

enclosing

def cl2 =

assertcl(

)==cl2(

)assertcl(

)==this

def enclosed =

.call()

}assert

enclosed()

== enclosed

}}

class

person

def p =

newperson

(name:

'igor'

)def cl =

cl.delegate = p

assertcl(

)=='igor'

def x =

1def gs =

"x = $"

assert gs ==

'x = 1'

//true

x =2

assert gs ==

'x = 2'

//false

原因:$對應的值只在第一次執行gs時被填入,未考慮後續x的變化

解決方法:

def x =

1def gs =

"x = $"

assert gs ==

'x = 1'

x =2

assert gs ==

'x = 2'

預定義閉包引數,返回乙個更少引數的閉包

def ncopies =

def twice = ncopies.

curry(2

)assert

twice

('bla')==

'blabla'

assert

twice

('bla')==

ncopies(2

,'bla'

)

右引數縮減

def ncopies =

def blah = ncopies.

rcurry

('bla'

)assert

blah(2

)=='blabla'

assert

blah(2

)==ncopies(2

,'bla'

)

def fib

fib =

assert

fib(15)

==610

// slow!

一種更快的寫法

fib =

.memoize()

assert

fib(25)

==75025

// fast!

def plus2  =

def times3 =

def times3plus2 = plus2 << times3

assert

times3plus2(3

)==11assert

times3plus2(4

)==plus2

(times3(4

))def plus2times3 = times3 << plus2

assert

plus2times3(3

)==15assert

plus2times3(5

)==times3

(plus2(5

))// reverse composition

assert

times3plus2(3

)==(times3 >> plus2)(3

)

def factorial

factorial =

factorial = factorial.

trampoline()

assert

factorial(1

)==1assert

factorial(3

)==1*

2*3assert

factorial

(1000

)// == 402387260.. plus another 2560 digits

Groovy閉包筆記

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

Groovy筆記 二 閉包

閉包應用模式 1.策略模式 def function closure clo function function 2.閉包引數 def closure closure new date string 3.模板方法模式 class resouces def write def read def clo...

groovy閉包基本用法

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