Groovy 之 Closure

给它的定义:

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' }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值