Groovy 之 Closure
发布时间:2020-12-14 16:44:43 所属栏目:大数据 来源:网络整理
导读:给它的定义: Closures are anonymous blocks of code that can accept parameters and can return a value. They can be assigned to variables and can be passed as parameters to methods. 匿名代码块; 可向它传入参数; 可被赋给变量; 自身可作为参数
给它的定义:
匿名代码块; Closure square = {
it * it
}
square 16
简单的Closure:def myClosure = { println 'Hello world!' }
//execute our closure
myClosure()
接受一个参数的Closure:def myClosure = {String str -> println str }
//execute our closure
myClosure('Hello world!')
一个参数时,在闭包内可以用it代替def myClosure = {println it } //execute our closure
myClosure('Hello world!')
接受多个参数def myClosure = {String str,int num -> println "$str : $num" }
//execute our closure
myClosure('my string',21)
参数类型是可选的,上面的还可以写成这样def myClosure = {str,num -> println "$str : $num" }
//execute our closure
myClosure('my string',21)
闭包可以引用创建它的上下文中的变量def myVar = 'Hello World!'
def myClosure = {println myVar}
myClosure()
闭包的上下文Context可利用setDelegate()来切换这个概念在后面会变的非常有用。 def myClosure = {println myVar}
MyClass m = new MyClass()
myClosure.setDelegate(m)
myClosure()
class MyClass {
def myVar = 'Hello from MyClass!'
}
在创建myClosure之时,myVar是不存在的,但在执行myClosure之前,将myClosure的context改变为MyClass 传递Closure参数下面是方法中传递Closure参数的多重写法 接受一个参数myMethod(myClosure)
如果只有一个参数,括号可省略myMethod myClosure in-line内联形式myMethod {println 'Hello World'}
两个参数myMethod(arg1,myClosure)
第二个参数为in-line形式myMethod(arg1,{ println 'Hello World' })
如果方法最后一个参数是闭包,那么可将其移出来myMethod(arg1) { println 'Hello World' }
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |