Groovy for Closure

本文详细介绍了Groovy语言中的闭包概念,包括闭包的基本定义、如何使用闭包定义和执行简单的代码块、闭包参数的传递方式以及闭包内的隐式变量等内容,并通过实例演示了闭包作为方法参数的应用。
What is a Closure?
什么是闭包?
Groovy闭包就像是”代码块”或是方法指示块(method pointer).这些代码块被定义在一起,然后在最后执行
Simple Example
def clos = { println "hello!" }
println "Executing the closure:"
clos()                           //prints "hello!"
注意到上面的例子,当闭包被呼叫时”hello”才打印出来,并不是在定义时.
当定义闭包时,它也能”界定”局部变量:
def localMethod() {
 def localVariable = new java.util.Date()
 return { println localVariable }
}
 
def clos = localMethod()
 
println "Executing the closure:"
clos()
Parameters( 参数 )
闭包的参数要在前面加 ->标记,就像这样:
def clos = { a, b -> print a+b }
clos( 5, 7 )                        //prints "12"
如果你的闭包中定义的参数少于两个可以省略掉 ->标记.
Implicit variables( 隐式变量 )
在闭包内,很多变量定义有其特殊含义:
 
It
 
如果你的闭包有一个单变元(single argument),你可以在闭包中省略参数定义,像这样:
def clos = { print it }
clos( "hi there" )               //prints "hi there"
 
this, owner, and delegate
 
this:正如在Java中,this代表了在闭包中定义的封装类(enclosing class)
 
owner:封闭地对象(the enclosing object)(this或者它周围的闭包)
 
delegate:默认情况下,与owner一样,只是在builder或ExpandoMetaClass是可改变的
 
例如 :
class Class1 {
 def closure = {
    println this.class.name
    println delegate.class.name
    def nestedClos = {
      println owner.class.name
    }
    nestedClos()
 }
}
 
def clos = new Class1().closure
clos.delegate = this
clos()
/* prints:
 Class1
 Script1
 Class1$_closure1 */
 
Closures as Method Arguments( 闭包的函数参数 )
当在 method中闭包作为最后一个参数,你可以定义内线闭包(closure inline):
def list = ['a','b','c','d']
def newList = []
 
list.collect( newList ) {
 it.toUpperCase()
}
println newList            // ["A", "B", "C", "D"]
在上面的例子中 ,collect方法收到一个List和一个闭包参数,下面的例子说明情况和上面例子一样(虽然比较啰嗦):
def list = ['a','b','c','d']
def newList = []
 
def clos = { it.toUpperCase() }
list.collect( newList, clos )
 
assert newList == ["A", "B", "C", "D"]
 
More Information( 更多信息 )
Groovy继承了java.lang.Object用以许多methods来作为闭包参数.参见GDK Extensions to Object中针对闭包的示例.
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值