什么是闭包(Groovy) flyleave ITeye技术网站

什么是闭包(Groovy) - flyleave - ITeye技术网站

Groovy的闭包就像一个代码段或者说方法指针。它是一段被定义并在稍后的时点上运行的代码。

Simple Example


Java代码  收藏代码
  1. def clos = { println "hello! }  





Java代码  收藏代码
  1. 示例: def clos = { println "hello!}  
  2.       println "Executing the closure:"  
  3.       clos()    

     





注意在上面的例子中,"hello"在闭包被调用的时候才打印出来,而不是在定义的时候。

Closures may be "bound" to variables within the scope where they are defined:

闭包可以与在特定范围内定义的变量绑定起来(这句不知翻译的对错,请看原文)


Java代码  收藏代码
  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()     //打印出当localVariables被创建时的时间  


参数:

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


Java代码  收藏代码
  1. def clos = { a, b -> print a+b }  
  2. clos( 57 )                       //prints "12"  




-> 这个符号是可选的,当你定义的闭包的参数小于两个时就可将其省略



隐含的变量

在闭包中,有几个变量有着特别的含义



it(注意是小写):

如果你的闭包定义仅含有一个参数,可以将其省略,Groovy自动用it来代替

比如:


Java代码  收藏代码
  1. def clos = { print it }  
  2. clos( "hi there" )              //prints "hi there"  




this, owner, 和 delegate



this :  如同在Java中一样,this 代表闭包被定义的类



owner : 包含闭包的对象,有可能是定义闭包的类或者是另外一个闭包



delegate : 默认与owner相同,but changeable for example in a builder or ExpandoMetaClass




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




作为方法参数的闭包



当一个方法的最后一个参数是闭包的时候,我们可以将闭包紧随其后定义,如


Java代码  收藏代码
  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"]  




上一个例子也可以用下面的方法实现,就是稍显冗长。




Java代码  收藏代码
  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

上文提到的 collect 就是这样一个例子 

collect(Collection collection) {closure} 返回一个集合,并将该集合的每一项添加到给定的集合中

原文地址:https://www.cnblogs.com/lexus/p/2650848.html