什么是闭包

一个groovy闭包就像一个代码块或者方法指针,他是定义然后执行的一段代码,但是他有一些特性:隐含变量,支持自由变量,支持currying 。

我们先来看看一些例子:

1 def clos = { println "hello!" }
2  
3 println "Executing the Closure:"
4 clos() //prints "hello!"

在上面的例子中”hello!”是因为调用clos()函数才打印出来的,而不是在定义的时候打印出来的。

参数

闭包的参数在->之前列出,比如:

1 def printSum = { a, b -> print a+b }
2 printSum( 57 //prints "12"

如果闭包的参数是少于2个的话,那么 ->是可以省略的。

Parameter notes

A Closure without -> , i.e. {} , is a Closure with one argument that is implicitly named as ‘it’. (see below for details) In some cases, you need to construct a Closure with zero arguments, e.g. using GString for templating, defining EMC Property etc. You have to explicity define your Closure as { -> } instead of just { }

You can also use varargs as parameters, refer to the Formal Guide for details. A JavaScript-style dynamic args could be simulated, refer to the Informal Guide.

自由变量

闭包能引用在参数列表中没有列出的变量,这些变量成为自由变量,他们的作用范围在他们定义的范围内:

1 def myConst = 5
2 def incByConst = { num -> num + myConst }
3 println incByConst(10// => 15

另外一个例子:

1 def localMethod() {
2  def localVariable = new java.util.Date()
3  return println localVariable }
4 }
5  
6 def clos = localMethod()
7  
8 println "Executing the Closure:"
9 clos() //prints the date when "localVariable" was defined

隐式变量

it

如果你有一个闭包但是只有一个参数,那么你可以省略这个参数,比如:

1 def clos = { print it }
2 clos( "hi there" //prints "hi there"

this, owner, and delegate

this : 和java中是一样的, this refers to the instance of the enclosing class where a Closure is defined

owner : the enclosing object (this or a surrounding Closure)

delegate : by default the same as owner, but changeable for example in a builder or ExpandoMetaClass

1 class Class1 {
2  def closure = {
3  println this.class.name
4  println delegate.class.name
5  def nestedClos = {
6  println owner.class.name
7  }
8  nestedClos()
9  }
10 }
11  
12 def clos = new Class1().closure
13 clos.delegate = this
14 clos()
15 /* prints:
16  Class1
17  Script1
18  Class1$_closure1 */

闭包作为方法参数

当一个方法使用闭包作为最后一个参数的话,那么就可以内嵌一个闭包,比如:

1 def list = ['a','b','c','d']
2 def newList = []
3  
4 list.collect( newList ) {
5  it.toUpperCase()
6 }
7 println newList // ["A", "B", "C", "D"]

在上面的collect方法中,他接受一个一个List和闭包,上面的代码等价于下面的代码:

1 def list = ['a','b','c','d']
2 def newList = []
3  
4 def clos = { it.toUpperCase() }
5 list.collect( newList, clos )
6  
7 assert newList == ["A""B""C""D"]

更多的信息:

Groovy继承了 java.lang.Object并且许多的 Collection 和Map 的许多方法都接受闭包作为参数的 See GDK Extensions to Object for practical uses of Groovy's Closures.

See Also:

 

groovy-闭包的更多相关文章

  1. Java8-Function使用及Groovy闭包的代码示例

    导航 定位 概述 代码示例 Java-Function Groovy闭包 定位 本文适用于想要了解Java8 Function接口编程及闭包表达式的筒鞋. 概述 在实际开发中,常常遇到使用模板模式的场 ...

  2. Groovy闭包详解

    Groovy闭包是一种可执行代码块的方法,闭包也是对象,可以向方法一样传递参数,因为闭包也是对象,因此可以在需要的时候执行,像方法一样闭包可以传递一个或多个参数.闭包最常见的用途就是处理集合,可以遍历 ...

  3. 谈谈Groovy闭包

    A closure is a function with variables bound to a context or environment in which it executes. 概述 闭包 ...

  4. Java8函数接口实现回调及Groovy闭包的代码示例

    本文适用于想要了解Java8 Function接口编程及闭包表达式的筒鞋. 概述 在实际开发中,常常遇到使用模板模式的场景: 主体流程是不变的,变的只是其中要调用的具体方法. 其特征是:   Begi ...

  5. lambda表达式和groovy闭包的区别

    groovy定义的闭包是 Closure 的实例,lambda表达式只是在特定的接⼝或者抽象类的匿名实现,他们之间最主要区别闭包可以灵活的配置代理策略⽽labmda表达式不允许

  6. Groovy闭包

    定义 闭包(Closure)是一种数据类型,它代表一段可执行的代码.它可以作为方法的参数,或者返回值,也可以独立运行,定义如下: def xxx = {parameters -> code}   ...

  7. groovy闭包科里化参数

    科里化闭包:带有预先绑定形参的闭包.在预先绑定一个形参之后,调用闭包时就不必为这个形参提供实参了.有助于去掉方法调用中的冗余重复. 使用curry方法科里化任意多个参数 使用rcurry方法科里化后面 ...

  8. Gradle学习之闭包

    Gradle中的闭包其实就等同于Groovy中闭包,Groovy是一种jvm语言,语法兼容于java,曾几何时,也在脚本语言中独树一帜,初学Gradle的时候,大家很容易被其语法所迷惑,由于Gradl ...

  9. 基于Groovy+HttpRestful的超轻量级的接口测试用例配置的设计方案及DEMO实现

    目标 设计一个轻量级测试用例框架,接口测试编写者只需要编写测试用例相关的内容(入参及结果校验),不需要理会系统的实现,不需要写跟测试校验无关的内容. 思路 测试用例分析 一个用例由以下部分组成: (1 ...

  10. 《Gradle权威指南》--Groovy基础

    No1: Groovy中分号不是必须的 No2: Groovy中,单引号和双引号都可以定义一个字符串常量,不同的是单引号标记的是纯粹的字符串常量,而不是对字符串里的表达式做运算,但是双引号可以. ta ...

随机推荐

  1. POJ 1141 Brackets Sequence

    Brackets Sequence Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 29502   Accepted: 840 ...

  2. js 与ios 交互的三种方法

    第一种:IOS拦截url  实现跳转 参考链接:http://www.cnblogs.com/pengyingh/articles/2354381.html IOS9.0 及以上支持 第二种:IOS ...

  3. Visual C#编写3D游戏框架示例

    你可能对实际地编写游戏代码期待已久了.由于DirectX SDK 2004年夏季更新包含了一个牢固的示例框架组件,并且它被设计成能在你自己的代码中直接使用,同时还为你处理了很多事务,所以你只要简单的使 ...

  4. [转]SRTM、ASTER GDEM等全球数字高程数据(DEM)下载方式简介

    之前写过一篇短文对比过几种数字高程数据的区别:5种全球高程数据对比,这篇文章简要介绍下如何下载这些数据.       1.DLR的数字高程数据.该数据也是SRTM(shuttle radar topo ...

  5. GEOS库的学习之二:简单几何图形的创建

    几何图形(Geometry)是geos里面基本的操作对象,因此Geometry类就是最重要的一个类 几何图形中主要有三个要素:点,线,面.横纵坐标构成点,多个点构成线,环线构成面,点线面混合构成几何集 ...

  6. [git]图解git常用命令

    本文图解git中最常用的命令.如果你稍微理解git的工作原理,这篇文章能够让你理解的更透彻. 基本用法 约定 命令详解 Diff Commit Checkout Detached HEAD(匿名分支提 ...

  7. 信息安全系统设计基础实验二 20135210&20135218

    北京电子科技学院(BESTI) 实     验    报     告 课程:信息安全系统设计基础                                          班级:1352 姓名 ...

  8. RedHat版的linux安装yum源及redis

    一.前言 最近正在学习redis,但是在安装redis的时候遇到很多坎,在此记录一下. 硬件环境:我用 VMware Workstation Pro 12 安装 Red Hat Enterprise ...

  9. 网页音乐突破金币(RMB)下载限制

    我平时有时间会跳跳舞 跳舞肯定要有音乐呀 于是在网上找音乐 好不容易找到了一个网站,里面有很多很全的音乐 正准备下载呢,尼玛居然要金币! 在这里解释一下,金币你可以通过回复帖子或者发帖子得到,但是数量 ...

  10. Android开发者资源大汇总

    本文总结了最新的Android开发资源.下面列出的资源都是常用的,每个Android程序员都应该知道,能大大方便App开发.Enjoy~ 来源:Android开发周刊 中文的Android开发信息,资 ...