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

闭包返回一个闭包例子(看起来像迭代)
[code]
def times= { x -> { y -> x * y }}
assert times(3)(4) == 12
[/code]
闭包简便写法
[code]
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
[/code]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值