Groovy的闭包
什么是闭包一个Groovy闭包就像一个"代码块"或函数指针。它是一个代码片段的定义和执行。它拥有一些像隐含变量一样的特定属性,用来支持currying和和自由变量(后面我们会提到)。下面我们先忽略细节,看一下下面的简单例子。 简单例子
def clos = { println "hello!" }
println "Executing the Closure:"
clos()
上述的闭包是在被调用的时候执行,而不是定义的时候。 参数闭包的参数位于
def printSum = { a,b -> print a+b }
printSum( 5,7 ) //prints "12"
参数说明一个像 自由变量(Free Variables)闭包可以引用变量未列出的参数列表。这样的变量被称之为自由变量(Free Variables),他们被“绑定”在变量定义的范围之内:
def myConst = 5
def incByConst = { num -> num + myConst }
println incByConst(10) // => 15
另外一个例子:
def localMethod() {
def localVariable = new java.util.Date()
return { println localVariable }
}
def clos = localMethod()
println "Executing the Closure:"
clos() //prints the date when "localVariable" was defined
隐含变量在groovy闭包当中,许多变量被定义成有特定的意义: it如果你有一个只含一个参数的闭包,你可能隐藏此参数,如下:
def clos = { print it }
clos( "hi there" ) //prints "hi there"
this,owner,and delegatethis:在java中,
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 */
闭包用作方法的参数当一个方法把闭包当做最后一个参数时,你可以定义一个行内闭包,如下:
def list = ['a','b','c','d']
def newList = []
list.collect( newList ) {
it.toUpperCase()
}
println newList // ["A","B","C","D"]
在上述的例子当中,
def list = ['a','d']
def newList = []
def clos = { it.toUpperCase() }
list.collect( newList,clos )
assert newList == ["A","D"]
更多Groovy继承自
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
