Closures and collection methods

In the last chapter, we encountered Groovy lists and saw some of the iteration functions, such as the each method:

def flintstones = ["Fred","Barney"]

flintstones.each {
    println "Hello, ${it}"
}

This looks like it could be a specialized control loop similar to a while loop. In fact, it is a call to the each method of Object. The each method takes a closure as one of its parameters, and everything between the curly braces {} defines another anonymous closure.

Closures defined in this way can look quite similar to code blocks, but they are not the same. Code defined in a regular Java or Groovy style code block is executed as soon as it is encountered. With closures, the block of code defined in the curly braces is not ...

Get Groovy for Domain-specific Languages - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.