Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using groovy.lang.Closure in Java application

I would like to use the Groovy Closure class in a Java application, but am having more trouble than expected. Here's what I have:

int count = 0;
groovy.lang.Closure closure = { count = 1 };

However, when I try to compile this using JDK 7, I get the error: illegal initializer for Closure

Am I missing something really obvious? Thanks for your help.

like image 505
user304582 Avatar asked Aug 30 '15 08:08

user304582


People also ask

How do you call a closure on Groovy?

We can pass a Closure as an argument to a method. Unary closures can use the implicit it parameter. We can assign a Closure to a variable and execute it later, either as a method or with call. Groovy determines the return type of the closures at runtime.

What is Groovy Lang closure?

A closure in Groovy is an open, anonymous, block of code that can take arguments, return a value and be assigned to a variable. A closure may reference variables declared in its surrounding scope.

What is the role of closure and listeners in Groovy?

6) Mention what is the role of closure and listeners in Groovy? Groovy does not support anonymous inner classes; it is possible to determine action listeners inline through the means of closures. In Groovy, listeners closure are used as a ListenerAdapter where only one method of interest is overridden.

What is a closure in Java?

Closures are the inline-function valued expressions which means that they are the class functions with bounded variables. Closures can be passed to another function as a parameter. A closure gives us access to the outer function from an inner function.


1 Answers

There's already an answer above, I am simply adding an working example.

Groovy Code that accepts closure,

public class GroovyService {

    Integer doSomething(Closure<Integer> fn) {
        fn()
    }
}

Calling groovy closure From java,

import groovy.lang.Closure;

public class JavaCanCallGroovy {

    public static void main(String[] args) {

        GroovyService service = new GroovyService();

        Integer data = service.doSomething(new Closure<Integer>(null) { //need to pass owner = null
            @Override
            public Integer call() {
                return 100;
            }
        });

        System.out.println(data);
    }
}

Call groovy closure from scala

import groovy.lang.Closure

object ScalaCanCallGroovy extends App {

  private val closure = new Closure[Integer]() {
    override def call() = 1
  }

  val groovyService = new GroovyService
  val data = groovyService.doSomething(closure)

  assert(data == 1)
}
like image 98
prayagupa Avatar answered Nov 07 '22 09:11

prayagupa