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
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