导航

Groovy系列 - 闭包Closure

Posted on 2012-05-26 18:08  eastson  阅读(491)  评论(0编辑  收藏  举报

闭包是什么?看看Groovy Documentation里面的定义:Closures are similar to Java's inner classes, except they are a single method which is invokable, with arbitrary parameters. 

 

我自己的理解:闭包就是一个method变量,可以有很多的参数。

 

简单的闭包实例:

def closure = { param -> println("hello ${param}") }
closure.call("world!")

closure = { greeting, name -> println(greeting + name) }
closure.call("hello ", "world!")

 

从上面的例子可以看出:

  • 闭包的定义放在{}中间。
  • 参数放在->符号的左边,语句放在->符号的右边。如果有多个参数,参数之间用逗号分割。
  • 使用call()可以执行闭包。

 

如果在->符号的左边没有指定参数,Groovy会默认一个it的参数:

def closure = { println "hello " + it }
closure.call("world!")

 

使用闭包可以很方便的处理集合:

[1, 2, 3].each({item -> println "${item}-"})
["k1":"v1", "k2":"v2"].each({key, value -> println key + "=" + value})

 

如果闭包是某个方法调用的最后一个参数,则闭包的定义允许放在方法调用圆括号的外边:

def fun(int i, Closure c) {
  c.call(i)
}

// put Closure out of ()
[1, 2, 3].each() { item -> print "${item}-" } // 1-2-3-
fun(123) { i -> println i } // 123

// omit ()
[1, 2, 3].each ({ item -> print "${item}-" }) // 1-2-3-

// omit enclosing ()
[1, 2, 3].each { item -> print "${item}-" } // 1-2-3-

// normal
[1, 2, 3].each(({ item -> print "${item}-" })) // 1-2-3-

// using the fun function to do the same thing
[1,2,3].each {fun(it,{item -> print "${item}-"})} // 1-2-3-

def closure = { i -> println i}

//[1, 2, 3].each() closure // error. closure has been previously defined

 

本文参考文档:http://groovy.codehaus.org/Quick+Start