Groovy Closure(闭包)-groovy-closure.md
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 | //闭包的参数为可选项 |
闭包可以访问外部变量,而方法(函数)则不能。
1 | def str = 'hello' |
闭包调用的方式有两种,闭包.call(参数)或者闭包(参数),在调用的时候可以省略圆括号。
1 | def closure = { |
闭包的参数是可选的,如果没有参数的话可以省略->
操作符。
1 | def closure = {println 'hello'} |
多个参数以逗号分隔,参数类型和方法一样可以显式声明也可省略。
1 | def closure = { String x, int y -> |
如果只有一个参数的话,也可省略参数的定义,Groovy提供了一个隐式的参数it来替代它。
1 | def closure = { it -> println it } |
闭包可以作为参数传入,闭包作为方法的唯一参数或最后一个参数时可省略括号。
1 | def eachLine(lines, closure) { |
关键变量this owner delegate
闭包的委托策略
//TODO
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 LT的编程笔记!