Groovy 之 Closure

来源:互联网 发布:尼尔森数据分析 编辑:程序博客网 时间:2024/05/15 01:57

给它的定义:

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 closuremyClosure()

接受一个参数的Closure:

def myClosure = {String str -> println str }//execute our closuremyClosure('Hello world!')

一个参数时,在闭包内可以用it代替

def myClosure = {println it }//execute our closuremyClosure('Hello world!')

接受多个参数

def myClosure = {String str, int num -> println "$str : $num" }//execute our closuremyClosure('my string', 21)

参数类型是可选的,上面的还可以写成这样

def myClosure = {str, num -> println "$str : $num" }//execute our closuremyClosure('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' }
0 0
原创粉丝点击