在 Groovy 中,闭包(Closure)是一个非常强大的特性。闭包是代码块,可以作为对象传递
和执行
。
它们不仅可以包含逻辑,还可以访问和修改其定义作用域中的变量。
闭包的基本语法
基本定义
{ [参数列表] -> 代码块 }
示例
// 无参数的闭包
def noParams = { println "Hello, Groovy!" }
noParams() // 调用闭包
// 带参数的闭包
def withParams = { name -> println "Hello, $name!" }
withParams("Alice")
// 多参数的闭包
def multiParams = { first, last -> println "Hello, $first $last!" }
multiParams("Alice", "Smith")
引用一个方法作为闭包
def doubleMethod2(entry){
//do sth
}
doubler2 = this.&doubleMethod2
闭包的基本使用
作为方法参数
作为方法参数—定义
// 使用默认参数类型({})
def benchmarkDefault(repeat, worker = {}) {
for (int i = 0; i < repeat; i++) {
worker.call(i)
}
}
// 显式声明 Closure 类型
def benchmarkExplicit(repeat, Closure worker) {
for (int i = 0; i < repeat; i++) {
worker.call(i)
}
}
//方法
作为方法参数-调用
闭包可以作为参数传递给方法,这使得 Groovy 非常适合用于 DSL(领域特定语言)和流畅的 API 设计。
def greet(Closure closure) {
closure("World") // 隐式调用
// closure.call("World") // 显示调用
}
greet({ println "Hello, $it!" })
greet(){println "Hello, $it!" }
greet{println "Hello, $it!" } // 常用方法
作为方法参数-归纳
a {}
:最简洁的闭包调用方式,常用于配置脚本和 DSL。a.call {}
:显式调用 call 方法,传递一个新的闭包。a.call({})
:显式调用 call 方法,将闭包括在括号中传递,语法稍冗长。a.call() {}
:结合方法调用和闭包传递,功能上与 a.call {} 相同,但语法更复杂。
实例&区别
// 定义一个方法 a,接受一个闭包作为最后一个参数
def a(Closure closure) {
closure.call()
}
// 1. 直接调用 a 并传递闭包
a {
println "Hello from a {}"
}
// 2. 调用 a 的 call 方法并传递闭包
a.call {
println "Hello from a.call {}"
}
// 3. 调用 a 的 call 方法,传递闭包作为参数
a.call({
println "Hello from a.call({})"
})
// 4. 调用 a 的 call 方法,传递闭包作为参数,使用空括号
a.call() {
println "Hello from a.call() {}"
}
闭包的参数
闭包的默认参数
如果闭包没有指定参数,Groovy 会使用默认参数 it
。
def greet = { println "Hello, $it!" }
greet("World")
闭包的参数数量
def callClosure(Closure closure) {
closure.getParameterTypes().size()
}
assert callClosure { a -> } == 1
assert callClosure { a, b -> } == 2
assert callClosure { a, b, c -> } == 3
闭包的返回值
def square = { int x -> x * 2 }
assert square(4) == 8
def add = { int x, int y -> return x + y }
assert add(3, 5) == 8
闭包的作用域
闭包可以访问定义它们的作用域中的变量。这使得闭包非常灵活和强大。
def outerVar = "I am outside!"
def closure = {
println outerVar
}
closure() // 输出: I am outside!
复杂一点的例子
class Mother {
int field = 1
int foo(){
return 2
}
Closure birth(param) {
def local = 3
def closure = { caller ->
// [this, field, foo(), local, param, caller, this.owner]
[this, field, foo(), local, param, caller]
}
return closure
}
}
Mother julia = new Mother()
closure = julia.birth(4)
context = closure(this)
println context[0].class.name // Mother
assert context[1..4] == [1,2,3,4]
println context[5] //scirpt name: helloworld@6e9c413e
assert context[5] instanceof Script
firstClosure = julia.birth(4)
secondClosure = julia.birth(4)
assert false == firstClosure.is(secondClosure)
Delegate
闭包有一个 delegate
属性,可以动态地改变闭包执行时的上下文。这在构建 DSL 时非常有用。
class Person {
String name
def sayHello() {
println "Hello, my name is $name"
}
}
def person = new Person(name: "Alice")
def closure = {
sayHello()
}
// 默认情况下,闭包的 delegate 是它自己
closure.delegate = person // 若没有这一行, 则会抛出`groovy.lang.MissingMethodException`
closure.resolveStrategy = Closure.DELEGATE_FIRST
closure() // 输出: Hello, my name is Alice
Resolve Strategy
resolveStrategy 决定了闭包如何解析未找到的属性和方法。常用的策略包括:
- Closure.OWNER_FIRST: 优先从闭包的 owner 中查找方法和属性。
- Closure.DELEGATE_FIRST: 优先从闭包的 delegate 中查找方法和属性。
- Closure.OWNER_ONLY: 仅从闭包的 owner 中查找方法和属性。
- Closure.DELEGATE_ONLY: 仅从闭包的 delegate 中查找方法和属性。
class Owner {
def greet() {
println "Hello from Owner!"
}
}
class Delegate {
def greet() {
println "Hello from Delegate!"
}
}
def owner = new Owner()
def delegate = new Delegate()
def closure = {
greet()
}
closure() // 输出:Hello from Origin-clsss!
def greet() {
println "Hello from Origin-clsss!"
}
closure() //输出: Hello from Origin-clsss!
closure.delegate = delegate
closure.owner = owner
closure.resolveStrategy = Closure.DELEGATE_FIRST
closure() // 输出: Hello from Delegate!
closure.resolveStrategy = Closure.OWNER_FIRST
closure() // 输出: Hello from Owner!
闭包的高级特性
curry
curry 的基本思想是一个多个参数的函数,传递较少的参数给函数来固定一些值
.
一个典型的例子是选择一些数 n 并且传递给函数与后面传递的单个参数进行相加.
def adder = { a, b -> a + b }
def addOne = adder.curry(1)
assert addOne(5) == 6
复杂一点的例子
假设你需要实现一个日志记录器,
- 它应该支持行数的过滤,
- 日志的格式化,
- 并且输出它们到一个设备上,
- 每一个记录器都应该是可配置的,
//configuration use
def configurator = { format, filter, line ->
filter(line) ? format(line) : null
}
// formatting use
def appender = { config,append,line ->
def out = config(line)
if (out) append(out)
}
def dateFormater = { line -> "${new Date()}: $line" }
def errorFilter = { line -> line.contains('ERROR') }
def consonleAppender = { line -> println line }
def configurator1 = configurator.curry(dateFormater, errorFilter)
def log1 = appender.curry(configurator1, consonleAppender)
log1('ERROR: something went wrong')
log1('INFO: everything is fine')
通过 isCase 方法进行分类
assert [1,2,3].grep{ it<3 } == [1,2]