jrharshath
jrharshath

Reputation: 26583

How to write java class methods that can accept groovy closures

Here's what I want to do:

I have a class called RowCollection which contains a collection of Row objects, with a method named edit, which is supposed to accept as a parameter another method (or closure) which operates on a Row object.

A groovy script will be using an object of this class in the following way:

rc.edit({ it.setTitle('hello world') }); // it is a "Row" object

My questions:

  1. what will the signature of RowCollection#edit look like?
  2. what can its implementation look like?

Upvotes: 3

Views: 585

Answers (2)

Ian Roberts
Ian Roberts

Reputation: 122424

As an alternative, if you make RowCollection implement Iterable<Row> and provide a suitable iterator() method then the standard Groovy-JDK magic applied to all classes will enable

rc.each { it.title = "hello world" }

and you get all the other iterator-backed GDK methods for free in the same way, including collect, findAll, inject, any, every and grep.

Upvotes: 3

jrharshath
jrharshath

Reputation: 26583

Okay - a little bit of digging, and here it is:

class RowCollection {
    private List<Row> rows;

    // ...

    public void edit(Closure c) {
        for(Row r : rows) {
            c.call(r);
        }
    }

    // ...
}

the class Closure is in groovy.lang package.

Upvotes: 2

Related Questions