Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write java class methods that can accept groovy closures

Tags:

java

groovy

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?
like image 410
jrharshath Avatar asked Jul 14 '26 05:07

jrharshath


2 Answers

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.

like image 104
Ian Roberts Avatar answered Jul 17 '26 17:07

Ian Roberts


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.

like image 20
jrharshath Avatar answered Jul 17 '26 16:07

jrharshath