The Curious Dev

Various programming sidetracks, devops detours and other shiny objects

Jun 23, 2012 - 2 minute read - Groovy

Groovy Closures

One of my favourite parts of Groovy is the functionality that Closures provide.

Basic Usage

A Closure is kind of like an anonymous method in Java, or a little like a function in JavaScript, except with a lot more functionality in a very simple and clean syntax.

def hello = { println 'Hello, World!' }

//prints "Hello, World!"

The above isn’t very useful on its own, but it is this structure that can be applied to other problems. We could add parameters and turn our little closure into a useful, callable chunk of code.

def extension = { filename ->
  return filename.substring(filename.lastIndexOf("."), filename.length())

println extension("A-File.With-Dots.In.The.Name.xml")
//prints ".xml"


One of the most common uses I have for closures is when iterating over a collection, rather than using a “for” loop, we can just call a “.each” on the collection and then call a closure:

def myList = ['one', 'two', 'three', 4, 5, "SIX"]
myList.each { i ->
  print i+', '

//prints "one ,two, three, 4, 5, SIX,"

Implicit Variables

The official Closures page covers this very well, but essentially there are several variables “built-in” that can be used in similar ways you might use the “this” keyword in Java:

  • it - the current object in a closure, i.e. the ‘i’ parameter in the example above
  • this
  • delegate
  • owner

Passing as Parameters

A closure can also be passed around as a parameter, though so far I’ve not found a need or really worked out how they could change the way I solve various problems … yet.

There are many uses for closures and they’re really quite integral to the structure of the language, I’m sure I’ll dig deeper in the future.