GDK对Object对象的扩展
Groovy添加了若干方法到java.lang.Object
当中,其中大部分处理类型作为集合或聚合,如列表或DOM节点。
Return Value |
Method |
Description |
Boolean |
any {closure} |
returns true if the closure returns true for any item |
List |
collect {closure} |
returns a list of all items that were returned from the closure |
Collection |
collect(Collection collection) {closure} |
same as above,but adds each item to the given collection |
void |
each {closure} |
simply executes the closure for each item |
void |
eachWithIndex {closure} |
same as each{} except it passes two arguments: the item and the index |
Boolean |
every {closure} |
returns true if the closure returns true for all items |
Object |
find {closure} |
returns the first item that matches the closure expression |
List |
findAll {closure} |
returns all items that match the closure expression |
Integer |
findIndexOf {closure} |
returns the index of the first item that matched the given expression |
**注释**以上表格只列出部分常用的方法,添加到`java.lang.Object`中的完整方法列表请参阅[GDK documentation on Object ](http://groovy.codehaus.org/groovy-jdk/java/lang/Object.html) 在Groovy当中,自从`return`关键字变成可选之后,闭包在这种情况下被当做`判断`,并且在闭包当中你无论给出的是什么表达式,返回的结果都是布尔型的。这种`判断`允许你以一种非常简洁的方式在集合对象上执行操作。 ### 例子
def numbers = [ 5,7,9,12 ]
assert numbers.any { it % 2 == 0 } //returns true since 12 is even
assert numbers.every { it > 4 } //returns true since all #s are > 4
assert numbers.findAll { it in 6..10 } == [7,9] //returns all #s > 5 and < 11
assert numbers.collect { ++it } == [6,8,10,13] //returns a new list with each # incremented
numbers.eachWithIndex{ num,idx -> println "$idx: $num" } //prints each index and number
原文地址
http://groovy.codehaus.org/GDK+Extensions+to+Object