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中针对闭包的示例.
本文详细介绍了Groovy语言中的闭包概念,包括闭包的基本定义、如何使用闭包定义和执行简单的代码块、闭包参数的传递方式以及闭包内的隐式变量等内容,并通过实例演示了闭包作为方法参数的应用。
1008

被折叠的 条评论
为什么被折叠?



