`
月迷津渡
  • 浏览: 102709 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

Groovy基础——Closure(闭包)详解

 
阅读更多

这篇文章介绍一下Closure的一些语法特性,以及它的使用方法,我们用规则以及代码的方法进行展现,和介绍MetaClass不同的是,这次我们将先列出规则,再贴上代码,让大家对所阐述的目标更加明确。

 

一、代码块(Blocking)

在介绍闭包前,先来讲几个Groovy中代码块的一些特性。

1.groovy的变量作用域和java相似,代码块内部声明的变量不能被外部访问调用。

2.对于Groovy Script, 用def定义的变量对binding.variables不可见。没有def等任何定义的可被binding.variable.参数名所访问。见代码:

 

def c = 5
assert c == 5
d = 6
assert d == 6 //def keyword optional because we're within a script context
assert binding.variables.c == null
assert binding.variables.d == 6
           //when def not used, variable becomes part of binding.variables

 3.对于第一条规则,有个例外,当变量没有def等任何定义时,该变量全局有效。见代码:

 

try{
  h = 9
  assert binding.variables.h == 9
}
assert h == 9
assert binding.variables.h == 9

 4.代码块可以嵌套,比如try代码块,这和Java是一样的。

 

二、闭包(Closures)

之前对代码块做了一些总结,这里言归正传,看看Groovy的闭包是多么的强大。

1. 闭包中可以包含代码逻辑,闭包中最后一行语句,表示该闭包的返回值,不论该语句是否冠名return关键字。如果c是无参数闭包,那么它的标准调用方法是c.call(),它的简洁调用方法是c()。见代码:

 

def a = 'coffee'
def c = {
  def b = 'tea'
  a + ' and ' + b //a refers to the variable a outside the closure,
                  //and is remembered by the closure
}
assert c() == 'coffee and tea' //short for c.call()

 2.闭包赋值给一个变量,和变量与变量间的赋值一致。见代码:

 

def c
try{
  def a = 'sugar'
  c = { a } //a closure always returns its only value
}
assert c() == 'sugar'
def d = c //we can also assign the closure to another variable
assert d() == 'sugar'

 3.调用闭包的方法等于创建一个闭包实例。对于相同闭包创建出来的不同实例,他们的对象是不同的。见代码:

 

c = { def e = { 'milk' }; e }
d = c
assert c == d
v1 = c()
v2 = c()
assert v1 != v2

 

三、闭包参数

这部分需要要讲的内容是闭包参数的运用和快捷,掌握了该部分内容有助于对于闭包得心应手地运用。

1.闭包的参数声明写在‘->’符号前,调用闭包的的标准写法是:闭包名.call(闭包参数)。见代码:

 

def toTriple = {n -> n * 3}
assert toTriple.call( 5 ) == 15

 

2.对于单一存在的参数it可以不用声明,直接使用it,it在Groovy中有着特殊的意义。见代码:

 

c = { it*3 }
assert c( 'run' ) == 'runrunrun'

 

3.当且仅当闭包中有且仅有一个参数,且不显示声明,it具有唯一参数引用的作用,其他情况下,如果在闭包参数声明中没有it,那么闭包的逻辑代码块中的it降级为普通的变量。见代码:

 

//c = { def it = 789 }
          //a compile error when uncommented: 'it' already implicitly defined
c = { value1 -> def it = 789; [value1, it] }
          //works OK because no 'it' among parameters
assert c( 456 ) == [456, 789]
c = {-> def it = 789; it } //zero parameters, not even 'it', so works OK
assert c() == 789
 

 

4.闭包中的参数名不能重复,it除外。见代码:

 

def name= 'cup'
//def c={ name-> println (name) } //a compile error when uncommented:
                                  //current scope already contains name 'name'
c= { def d= { 2 * it }; 3 * d(it) }
      //'it' refers to immediately-surrounding closure's parameter in each case
assert c(5) == 30

 

5.如果在脚本范围内Scope已经有it的定义声明,如果闭包中再使用it特性,那脚本中的it就近表示闭包中的参数,而owner.it表示脚本范围的it参数。这个和java中的this有几分相似。见代码:

 

it= 2
c= { assert it == 3; assert owner.it == 2 }
c(3) 

6. 我们可以将闭包作为参数传入另外一个闭包,同时可以从一个闭包返回一个闭包。

 

toTriple = {n -> n * 3}
runTwice = { a, c -> c( c(a) )}
assert runTwice( 5, toTriple ) == 45

def times= { x -> { y -> x * y }}
assert times(3)(4) == 12

 7.闭包的一些快捷写法,当闭包作为闭包或方法的最后一个参数。可以将闭包从参数圆括号中提取出来接在最后,如果闭包是唯一的一个参数,则闭包或方法参数所在的圆括号也可以省略。对于有多个闭包参数的,只要是在参数声明最后的,均可以按上述方式省略。见代码:

 

def runTwice = { a, c -> c(c(a)) }
assert runTwice( 5, {it * 3} ) == 45 //usual syntax
assert runTwice( 5 ){it * 3} == 45
    //when closure is last param, can put it after the param list

def runTwiceAndConcat = { c -> c() + c() }
assert runTwiceAndConcat( { 'plate' } ) == 'plateplate' //usual syntax
assert runTwiceAndConcat(){ 'bowl' } == 'bowlbowl' //shortcut form
assert runTwiceAndConcat{ 'mug' } == 'mugmug'
    //can skip parens altogether if closure is only param

def runTwoClosures = { a, c1, c2 -> c1(c2(a)) }
    //when more than one closure as last params
assert runTwoClosures( 5, {it*3}, {it*4} ) == 60 //usual syntax
assert runTwoClosures( 5 ){it*3}{it*4} == 60 //shortcut form

8.闭包接受参数的规则,会将参数列表中所有有键值关系的参数,作为一个map组装,传入闭包作为调用闭包的第一个参数。见代码:

 

def f= {m, i, j-> i + j + m.x + m.y }
assert f(6, x:4, y:3, 7) == 20

def g= {m, i, j, k, c-> c(i + j + k, m.x + m.y) }
assert g(y:5, 1, 2, x:6, 3){a,b-> a * b } == 66

9.闭包提供了询问自己参数个数的方法,无论在闭包内或者闭包外。见代码:

 

c= {x,y,z-> getMaximumNumberOfParameters() }
assert c.getMaximumNumberOfParameters() == 3
assert c(4,5,6) == 3

10.闭包可以将其最后的参数设置其默认的取值。见代码:

 

def e = { a, b, c=3, d='a' -> "${a+b+c}$d" }
assert e( 7, 4 ) == '14a'
assert e( 9, 8, 7 ) == '24a' //override default value of 'c'

11.闭包可以通过定义最后一个参数声明为Object[],来获取任意多个参数。同时,在闭包的逻辑处理中要使用这些参数则需要使用数组的each方法。

 

def c = { arg, Object[] extras ->
  def list= []
  list<< arg
  extras.each{ list<< it }
  list
}
assert c( 1 )          == [ 1 ]
assert c( 1, 2 )       == [ 1, 2 ]
assert c( 1, 2, 3 )    == [ 1, 2, 3 ]
assert c( 1, 2, 3, 4 ) == [ 1, 2, 3, 4 ]

12.如果闭包的参数声明中没有list,那么传入参数可以设置为list,里面的参数将分别传入闭包参数。见代码:

 

def c= {a, b, c-> a + b + c}
def list=[1,2,3]
assert c(list) == 6

13.闭包有一个curry方法,该方法的作用是锁定闭包的首个参数。类似于java中的方法重载。见代码:

 

def concat = { p1, p2, p3 -> "$p1 $p2 $p3" }
def concatAfterFly = concat.curry( 'fly' )
assert concatAfterFly( 'drive', 'cycle' ) == 'fly drive cycle'
def concatAfterFlySwim = concatAfterFly.curry( 'swim' )
assert concatAfterFlySwim( 'walk' ) == 'fly swim walk'

14.闭包是可嵌套的。见代码:

 

def gcd //predefine closure name
gcd={ m,n-> m%n==0? n: gcd(n,m%n) }
assert gcd( 28, 35 ) == 7

15.可以在闭包中用call闭包进行迭代。见代码:

 

def results = [];
{ a, b ->
  results << a
  a<10 && call(b, a+b)
}(1,1)
assert results == [1, 1, 2, 3, 5, 8, 13]  // Fibonacci numbers
 

以上就是所有闭包需要掌握的基本语法。

分享到:
评论
3 楼 u010753172 2018-08-13  
fruwei 写道
调用闭包的方法等于创建一个闭包实例。对于相同闭包创建出来的不同实例,他们的对象是不同的。
有点疑问
其实不一样的主要是因为
c = { def e = { 'milk' }; e }   
c()每次都反回的e是不同的,而不是相同闭包创建的闭包实例不同
比如例子:
c = { def e ='milk';e}
v1 = c()
v2 = c()
assert v1 == v2

重点是‘调用闭包的方法等于创建一个闭包实例’这句话表述有问题,博主要是先放出下面的例子,再以此作为解释就好理解一点了。

调用闭包cA就是执行cA的闭包体,本身根本就没有会创建新的闭包实例的说法,不知道的还以为每次调用闭包就会创建一个什么闭包实例,这很容易误导别人。
而如果cA的闭包体中声明定义了某个闭包变量cB,那么每次调用闭包cA时就会重新声明和定义一个新的cB(闭包实例),每次声明定义的cB指向的都不是同一个闭包实例。这其实换成其他类型的变量也一样,创建出来的一样是不同的对象(字符串常量和其他基础数据类型缓存范围内的值等除外),跟是不是闭包没有必然联系。

因此博主的这条总结其实意义不大甚至可能会误导别人……当然其它都很精彩!
2 楼 fruwei 2017-03-23  
调用闭包的方法等于创建一个闭包实例。对于相同闭包创建出来的不同实例,他们的对象是不同的。
有点疑问
其实不一样的主要是因为
c = { def e = { 'milk' }; e }   
c()每次都反回的e是不同的,而不是相同闭包创建的闭包实例不同
比如例子:
c = { def e ='milk';e}
v1 = c()
v2 = c()
assert v1 == v2
1 楼 aplixy 2016-05-14  
讲的很详细,谢谢分享

相关推荐

    Groovy基本语法.pdf

    1. **Closure(闭包)支持**:闭包是Groovy的一个核心特性,允许定义无名函数,通常作为方法参数传递。 - **定义与使用**:闭包使用大括号`{}`定义,参数列表放在闭包体前,使用竖线`|`分隔。 - **示例**: ```...

    groovy快速入门指南(中文)

    ### Groovy 快速入门指南知识点详解 #### 一、集合操作 Groovy 提供了对集合的强大支持,包括 `List` 和 `Map` 的多种操作方式。 **1. List** - **定义与访问** - Groovy 中的 `List` 可以包含不同类型的元素。...

    Groovy_快速入门.doc

    ### Groovy 快速入门知识点详解 #### 一、Groovy基础语法介绍 Groovy是一种灵活的编程语言,运行在Java平台上,具有简洁且强大的特性。Groovy支持面向对象编程和函数式编程,并且能够与Java无缝集成。下面将详细...

    Groovy入门

    - **闭包 (Closure)**:Groovy 中的重要特性之一,类似于 Java 的 Lambda 表达式,但功能更强大。 - 定义闭包使用 `{}`,闭包中的 `it` 参数代表传递给闭包的第一个参数。 - 闭包可以作为参数传递给其他函数或存储...

    简易groovy教程

    1. **闭包(Closure)支持**:闭包是Groovy的核心特性之一,允许函数被当作第一类公民对待。闭包可以通过`{}`定义,并通过`call`方法调用。闭包可以携带上下文环境,能够访问定义时的作用域。 2. **本地List和Map语法*...

    groovy-demo-java-for-refactor:在演示期间用于重构为Groovy的示例Java代码

    例如,Groovy的闭包(Closure)可以简化迭代和回调函数的编写,而Java则需要使用匿名内部类来实现类似功能。 3. **重构过程** 项目中的Java代码是经过精心选择的,涵盖了常见的类、方法和控制结构,如循环、条件...

    J1_2006_Grails_PowerPoint_v1.ppt

    - **Closure Support**:Groovy中的闭包是一种强大的功能,可以用来简化复杂操作,特别是在处理函数式编程任务时。 3. **Grails框架组件** - **MVC架构**:Grails基于经典的MVC模式,分离业务逻辑、数据模型和...

Global site tag (gtag.js) - Google Analytics