Skip to end of metadata
Go to start of metadata

Groovy adds a number of methods to java.lang.Object, most of which deal with types that serve as collections or aggregates, such as Lists or DOM Nodes.

Return Value




any {closure}

returns true if the closure returns true for any item


collect {closure}

returns a list of all items that were returned from the closure


collect(Collection collection) {closure}

same as above, but adds each item to the given collection


each {closure}

simply executes the closure for each item


eachWithIndex {closure}

same as each{} except it passes two arguments: the item and the index


every {closure}

returns true if the closure returns true for all items


find {closure}

returns the first item that matches the closure expression


findAll {closure}

returns all items that match the closure expression


findIndexOf {closure}

returns the index of the first item that matched the given expression

See the GDK documentation on Object for the complete list of added methods.

Since the "return" keyword is optional in Groovy, closures in this context act as "predicates" and return the boolean result of whatever expression you given in your closure. These predicates allow you to apply perform operations on aggregate objects in a very concise manner.


  • No labels

1 Comment

  1. Groovy's Object.with(closure) method doesn't constitute a 'scope' and in fact global variables actually shadow the object instance ones.

    Consider this script

    Execution in GroovyConsole gives:

    Note how $x is resolved to the global 'x'; one should always use $it.x.

    This example was developed with Groovy 1.6.3.

    It's not really a hindsight it makes sense (as is the way with hindsight (wink)).

    It is rather surprising when one comes across it intially, however.

    The tip for novice players is: always use the with closure's parameter to access fields. Always.