Groovy - closure

Summary

  • closure 翻译成闭包,这里我们先不要翻译过来。它是 Groovy 的一个强大的特性。
  • closure 中可以包含代码逻辑,最后一行语句,表示返回值,也可以显示的使用return关键字。
  • 我们可以将 closure 作为参数传入另外一个 closure,同时可以从一个 closure 返回一个 closure。

定义&调用&返回值

  • 默认定义完成的时候它不会执行代码,需要在调用的时候执行代码。
  • 注意:每次调用 closure 的时候,会创建出一个 closure 对象。
// 定义一个 closure 赋值给一个变量。
def x = {
def y = 1
// 返回 y,也可以使用 return y
y
}
// 调用
x.call()
x()

closure 参数

  • 参数定义写在 -> 符号前,调用的时候就想调用方法一样,直接在括号里面写入参数。
  • 参数名称不能重复,但是如果一个 closure 嵌套 另外一个 closure,他们都有一个参数,用默认的 it 没有问题。
// 基本的写法
def closure = { x -> x * 3 }
// 简写,如果 closure 有且仅有一个参数,可以直接使用 `it` 这个特殊的变量来替代。
def closure = { it * 3 }
// 两个参数
def closure = { int a, int b -> a + b }
// 不接受参数的 closure
def closure = { -> 88}
// Closure 接收可长度可变的 param。
def closure = { String... args1 -> args1.join(" ")}
println closure("Hello", "Closure!")

Method 使用 Closure 作为 param

class Main {
// 定义一个 method,使用 Closure 对象作为 param
static def methodWithClosureParam(Closure closure){
closure()
}
static def methodWithClosureParamEnd(String str, Closure closure){
println(str)
closure()
}
static void main(args) {
// Closure 实际上就是一个 groovy.lang.Closure 对象。
def closure = { println "Closure!"}
println closure instanceof Closure // true
// 调用上面方法,传递一个 Closure 对象给它
methodWithClosureParam {println "Groovy 1"} // 可以直接在这里定义。
methodWithClosureParam closure // 不使用小括号。
methodWithClosureParam(closure) // 传统的方式,使用小括号。
// 如果 method 的最后一个 param 是 Closure 对象,可以使用如下方式调用。
methodWithClosureParamEnd("Param One", closure)
methodWithClosureParamEnd("Param One", { println "Closure!"})
methodWithClosureParamEnd("Param One") { println "Closure!"}
}
}

Closure 中的 this 关键字

  • 代表 Closure 所在的类的一个对象。
class Test {
void run() {
// Closure 中的 this 引用的是该 class 的 Object。
def whatIsThis = { this }
println whatIsThis() == this
println this
}
}
class Main {
static void main(args) {
def test = new Test()
test.run() // true Test@212bf671
println test // Test@212bf671
}
}

Closure 中的 owner 对象

  • Closure 的 owner 就是直接包含 Closure 的类或者 Closure 对象,也就是说如果 Closure 直接定义在类中,那么 owner 就是类的对象,如果 Closure 直接定义在 Closure 中,那么 owner 就是 Closure 对象。
class Test {
class Inner {
def closure = { owner }
}
void run() {
Closure closure = { owner }
println closure() == this
println this
}
}

Closure 的 delegate

Closure 的一些常用方法

  • closure.getMaximumNumberOfParameters() 获取该 closure 可接收的参数个数。

Reference

https://www.jianshu.com/p/c02a456e1943

posted @   duchaoqun  阅读(253)  评论(0编辑  收藏  举报
编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
点击右上角即可分享
微信分享提示