Summary
- closure 翻译成闭包,这里我们先不要翻译过来。它是 Groovy 的一个强大的特性。
- closure 中可以包含代码逻辑,最后一行语句,表示返回值,也可以显示的使用return关键字。
- 我们可以将 closure 作为参数传入另外一个 closure,同时可以从一个 closure 返回一个 closure。
定义&调用&返回值
- 默认定义完成的时候它不会执行代码,需要在调用的时候执行代码。
- 注意:每次调用 closure 的时候,会创建出一个 closure 对象。
| |
| def x = { |
| def y = 1 |
| |
| y |
| } |
| |
| |
| x.call() |
| x() |
closure 参数
- 参数定义写在
->
符号前,调用的时候就想调用方法一样,直接在括号里面写入参数。
- 参数名称不能重复,但是如果一个 closure 嵌套 另外一个 closure,他们都有一个参数,用默认的 it 没有问题。
| |
| def closure = { x -> x * 3 } |
| |
| |
| def closure = { it * 3 } |
| |
| |
| def closure = { int a, int b -> a + b } |
| |
| |
| def closure = { -> 88} |
| |
| |
| def closure = { String... args1 -> args1.join(" ")} |
| println closure("Hello", "Closure!") |
Method 使用 Closure 作为 param
| class Main { |
| |
| |
| static def methodWithClosureParam(Closure closure){ |
| closure() |
| } |
| |
| static def methodWithClosureParamEnd(String str, Closure closure){ |
| println(str) |
| closure() |
| } |
| |
| static void main(args) { |
| |
| def closure = { println "Closure!"} |
| println closure instanceof Closure |
| |
| |
| methodWithClosureParam {println "Groovy 1"} |
| methodWithClosureParam closure |
| methodWithClosureParam(closure) |
| |
| |
| methodWithClosureParamEnd("Param One", closure) |
| methodWithClosureParamEnd("Param One", { println "Closure!"}) |
| methodWithClosureParamEnd("Param One") { println "Closure!"} |
| |
| } |
| } |
Closure 中的 this 关键字
| class Test { |
| void run() { |
| |
| def whatIsThis = { this } |
| println whatIsThis() == this |
| println this |
| } |
| } |
| |
| class Main { |
| static void main(args) { |
| def test = new Test() |
| test.run() |
| println test |
| } |
| } |
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
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .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 中如何实现缓存的预热?