Groovy闭包

1.闭包可以是指针,也可以直接调用,还可以将其作为参数传递:
def closure = {x-> x*3}
closure.call('h') //Result: "hhh"

def method(clo) {
clo.call('h')
}
method(closure) //Result: "hhh"
method() {x-> x*3} //Result: "hhh"
method {x-> x*3} //Result: "hhh"
method closure //Result: "hhh"

调用闭包也可以省略call()
def closure = {x-> x*3}
closure('h') //Result: "hhh"

当方法只有一个参数时,可以省略括号调用,如下两种调用方式都是一样的(闭包也是一样):
def method(x) {
println x
}
method 5
method(5)

def closure = {x-> println x}
closure 'h'
closure('h')
closure.call('h')

2.闭包和方法一样,形参个数必须和实参个数相等,也可以和方法一样使用默认参数:
//方法
def method(x, y = 'h') {
return y*x
}
method(3) Result: "hhh"
method(3,'k') Result: "kkk"

//闭包
def closure = {x,y='h'->
return y*x
}
closure 3 //Result: "hhh"
closure(3,'k') //Result: "kkk"

3.作用范围,闭包体内只能使用和闭包同一级的引用:
def name = 'Bruce'
def greeting = {println "Hi,${name}.Nice to see you"}
greeting() //Hi,Bruce.Nice to see you

name = 'Phil'
greeting() //Hi,Phil.Nice to see you

def method(closure) {
name = 'Divid'
//can not affect closure
closure() //Hi,Phil.Nice to see you
}
method(greeting)

4.应用部分:
def subtract = {x,y->
println x - y
}
//subtract.curry(20)操作会返回{y-> println 20 - y},即把第一个形参删掉,以实参替换闭包体中所有的被删除掉的形参
def subClosure = subtract.curry(20)
subClosure.call(5) //15

5.闭包组合,可以使用组合来构造出完成复杂任务的闭包组:
def composition = {a,b,c->a(b(c))}
def multiply1 = {x->return 3 * x}
def multiply2 = {x->return 4 * x}
composition(multiply1,multiply2,5) //Result: 60
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值