Groovy2.0 闭包

本代码示例为官方网站上示例
def a = 'coffee'
def c = {
  def b = 'tea'
  a + ' and ' + b
                  
}
assert c() == 'coffee and tea'

def c
try{
  def a = 'sugar'
  c = { a } //a closure always returns its only value
}
assert c() == 'sugar'
def d = c //we can also assign the closure to another variable
assert d() == 'sugar'


c = { def e = { 'milk' }; e }
d = c
assert c == d
v1 = c()
v2 = c()
assert v1 != v2

闭包参数示例
def f = { list, value -> list << value }
x = []
f(x, 1)
f(x, 2,) //trailing comma in argument list OK
f(x, 3)
assert x == [1, 2, 3]

it 为闭包的默认参数
c = { it*3 }
assert c( 'run' ) == 'runrunrun'

如果不定义参数,也是ok的
c = { value1 -> def it = 789; [value1, it] }
          //works OK because no 'it' among parameters
assert c( 456 ) == [456, 789]
c = {-> def it = 789; it } //zero parameters, not even 'it', so works OK
assert c() == 789

参数名不能重复,除了'it'
def name= 'cup'
//def c={ name-> println (name) } //name 重复了 会报错
c= { def d= { 2 * it }; 3 * d(it) }
      //'it' refers to immediately-surrounding closure's parameter in each case
assert c(5) == 30

owner.it是指外面的变量it( 注意 如果外面的it 定义为def it=2 ,将会报错)
owner是指外部定义的那些不带def 的变量
it= 2
c= { assert it == 3; assert owner.it == 2 }
c(3)

还可以在闭包中嵌套闭包
toTriple = {n -> n * 3}
runTwice = { a, c -> c( c(a) )}
assert runTwice( 5, toTriple ) == 45

闭包返回一个闭包例子(看起来像迭代)
def times= { x -> { y -> x * y }}
assert times(3)(4) == 12

闭包简便写法
def runTwice = { a, c -> c(c(a)) }
assert runTwice( 5, {it * 3} ) == 45 //usual syntax
assert runTwice( 5 ){it * 3} == 45
    //when closure is last param, can put it after the param list

def runTwiceAndConcat = { c -> c() + c() }
assert runTwiceAndConcat( { 'plate' } ) == 'plateplate' //usual syntax
assert runTwiceAndConcat(){ 'bowl' } == 'bowlbowl' //shortcut form
assert runTwiceAndConcat{ 'mug' } == 'mugmug'
    //can skip parens altogether if closure is only param

def runTwoClosures = { a, c1, c2 -> c1(c2(a)) }
    //when more than one closure as last params
assert runTwoClosures( 5, {it*3}, {it*4} ) == 60 //usual syntax
assert runTwoClosures( 5 ){it*3}{it*4} == 60 //shortcut form


你可能感兴趣的:(闭包,groovy)