2、闭包 
(1)概述 
l         闭包是一种传递执行代码块的强大方法。 
l         可以把闭包看作Java中的匿名内类,但是只有单一的(匿名)方法。 
l         闭包可以被用作循环的一种替代方法 
[1, 2, 3, 4].each { println(it) } 
l         使用闭包可以使异常处理和关闭资源变得更简单,具体例子请参看Groovy SQL 
(2)比较闭包和匿名内类 
l         不同于Java匿名内类,Groovy 支持“true closures”:状态可以被传递到闭包外部 
l         局部变量在闭包创建时可以被使用和修改;闭包中创建的任何变量可以作为局部变量,对外部可见 
l         看下面的例子: 
count = 0 last = 0 [1, 2, 3, 4].each { count += it; last = it } println("the sum is ${count} and the last item was ${last}") 
输出结果:the sum is 10 and the last item was 4 
(3)闭包是普通对象 
l         闭包是在需要时被传递和调用的对象 
l         因此可以象下面一样使用: 
c = { println("Hello ${it}") }c.call('James')c.call('Bob') 
l         闭包会被编译成扩展groovy.lang.Closure类的新类 
l         下面的省略写法是等价的 
c = { println("Hello ${it}") }c('James')c('Bob') 
(4)闭包的参数 
l         闭包可以有任意数目的参数 
l         缺省情况,闭包具有单个缺省参数:“it” 
l         你可以在闭包声明的开始部分指定参数列表 
c = { a, b, c | println("Hello ${a} ${b} ${c}") }c('cheese', 234, 'gromit') 
l         下面是另一个使用两个参数的有用例子,在《Groovy快速入门》已经讲过: 
value = [1, 2, 3].inject('counting: ') { str, item | str + item }assert value == "counting: 123"   value = [1, 2, 3].inject(0) { count, item | count + item }assert value == 6  
 
  |