title: Groovy Closure(闭包)date: 2021-07-31 17:41:37.779

updated: 2021-07-31 22:17:34.781
url: /?p=397
categories: Groovy
tags:

闭包

闭包的定义与使用:匿名内联函数,也称为一个闭包。

本质上说,闭包是将函数内部和函数外部连接起来的桥梁。

闭包在 Groovy 中是groovy.lang.Closure类的实例,这使得闭包可以赋值给变量,或者作为参数传递。

1
2
//闭包的参数为可选项
def closure = { [closureParameters -> ] statements }

闭包可以访问外部变量,而方法(函数)则不能。

1
2
3
4
5
def str = 'hello'
def closure={
println str
}
closure()//hello

闭包调用的方式有两种,闭包.call(参数)或者闭包(参数),在调用的时候可以省略圆括号。

1
2
3
4
5
6
7
def closure = {
param -> println param
}

closure('hello')
closure.call('hello')
closure 'hello'

闭包的参数是可选的,如果没有参数的话可以省略->操作符。

1
2
def closure = {println 'hello'}
closure()

多个参数以逗号分隔,参数类型和方法一样可以显式声明也可省略。

1
2
3
def closure = { String x, int y ->                                
println "hey ${x} the value is ${y}"
}

如果只有一个参数的话,也可省略参数的定义,Groovy提供了一个隐式的参数it来替代它。

1
2
3
4
def closure = { it -> println it } 
//和上面是等价的
def closure = { println it }
closure('hello')

闭包可以作为参数传入,闭包作为方法的唯一参数或最后一个参数时可省略括号。

1
2
3
4
5
6
7
8
9
def eachLine(lines, closure) {
for (String line : lines) {
closure(line)
}
}

eachLine('a'..'z',{ println it })
//可省略括号,与上面等价
eachLine('a'..'z') { println it }

关键变量this owner delegate

闭包的委托策略

//TODO