什么是闭包

一个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. 转: 在创业公司使用C++

    from: http://oicwx.com/detail/827436 在创业公司使用C++ 2016-01-04开发资讯 James Perry和朋友创办了一家公司,主要是做基于云的OLAP多维数 ...

  2. C++容器的复制

    C++容器的复制不同于Java Java是引用复制,复制的仅仅是对象的引用, 在需要复制容器内对象的副本集合的情况,需要使用Clone方法,而且要注意clone方法的浅拷贝 深拷贝 C++的容器复制 ...

  3. zepto.js 源码解析

    http://www.runoob.com/w3cnote/zepto-js-source-analysis.html Zepto是一个轻量级的针对现代高级浏览器的JavaScript库, 它与jqu ...

  4. Vim中split的使用方法

    Vim中split的使用方法 一.作用 用split可以显示两个不同的文件:或者同时显示一个文件的两个不同地方:又或者并排比较两个文件.这一切都可以通过分割窗口实现.如下图,左边的两个窗口是mytoo ...

  5. 团购、定时抢购倒计时js版

     <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org ...

  6. LeetCode:Search in Rotated Sorted Array I II

    LeetCode:Search in Rotated Sorted Array Suppose a sorted array is rotated at some pivot unknown to y ...

  7. Jenkins入门系列之——00答疑解惑

    写在最前的总结:Jenkins其实就是一个工具,这个工具的作用就是调用各种其他的工具来达成你的目的.比如你要获取Subversion上最新的源代码,Jenkins会去调用SVNKIT(插件的核心Jar ...

  8. Spring Cache和MyBatis的使用

    1.http://www.importnew.com/22757.html    spring chache缓存的使用. 2.http://www.importnew.com/22783.html   ...

  9. threejs构建web三维视图入门教程

    本文是一篇简单的webGL+threejs构建web三维视图的入门教程,你可以了解到利用threejs创建简单的三维图形,并且控制图形运动.若有不足,欢迎指出. 本文使用的框架是three.js gi ...

  10. 数据结构之链表、栈和队列 java代码实现

    定义抽象节点类Node: package cn.wzbrilliant.datastructure; /** * 节点 * @author ice * */ public abstract class ...