Groovy - Converting Methods to Closures

One of the important characteristics of Groovy closure is that they are first class - closures can be passed as arguments to other closures and functions.

More details on higher order functions in this post.

Suppose you have a piece of functionality available as a method and you want to pass that method as an argument to a higher order function. Now should you go ahead and duplicate the functionality in a new closure? If you do that, it will be clearly a violation of DRY principle.

Consider the following example.

class Operations {
    def increment(def number) {
        number + 1
    }
}
def numbers = [1, 2, 3, 4]
//println numbers.collect(<closure equivalent of increment>)

Method increment is defined in class Operations. We want to invoke collect on numbers with a closure that increments the given number. Fortunately, you don't have to rewrite increment as a closure just to be able to pass to collect! Groovy provides a way to convert existing methods to closures, without you having to rewrite them.

def operations = new Operations()
println numbers.collect(operations.&increment)

If the method is an instance method, you can prefix '&' to the method name on an object and get a closure equivalent. If the method is a static method you would use the class name instead of the object.

class Operations {
    def increment(def number) {
        number + 1
    }

    def static decrement(def number) {
        number - 1
    }
}

def numbers = [1, 2, 3, 4]
def operations = new Operations()
println numbers.collect(operations.&increment)
println numbers.collect(Operations.&decrement)