16

I'm learning about Java 8 new feature Lambda expressions. This is my "HelloWorld" class using Lambda expression

public class LambdaHelloWorld {
    interface HelloWorld {
        String sayHello(String name);
    }

    public static void main(String[] args) {          
         HelloWorld helloWorld = (String name) -> { return "Hello " + name; };
         System.out.println(helloWorld.sayHello("John Doe"));
    }
}

This style is so similar to Groovy closure. This is groovy "HelloWorld"

def sayHello(name) {
        println("Hello $name!")
}

def clos = {name -> sayHello(name)} 
clos.call('John Doe')

I think these two codes are less difference between each others.Is Java Lambda expression is similar logic or style of Groovy closure?

2
  • Instead of (String name) -> { return "Hello " + name; } you can simply write name -> "Hello "+name which is much shorter. By the way, without knowing much about Groovy, the examples do not look equivalent to me. The Java example is a function mapping a String value to a String value while your Groovy example looks like an action consuming a String.
    – Holger
    Aug 29, 2014 at 9:39
  • 1
    @Holger or, even shorter, "Hello "::concat
    – Misha
    Aug 29, 2014 at 11:44

3 Answers 3

31

Implementing a so-called functional interface in Java 8 (with lambdas) or in Groovy (with closures) looks quite the same, but underlying mechanisms are pretty different. Let's take the java.util.function.Consumer functional interface as an example. We use it to call the new Java 8 forEach() method on a hypothetic java.util.List instance called myList.

In Java it looks like this:

myList.forEach ((s) -> System.out.println(s));

The same in Groovy:

myList.forEach { s -> println s }

Both compilers generate new Classes from the lambda / closure code. The class generated by Java 8 implements the target interface (Consumer in this case), not derived from anything, similar to an embedded anonymous class like this:

myList.forEach(new Consumer<Object>() {
    @Override
    public void accept (Object s) {
        System.out.println(s);
    }
});

In contrast, what Groovy generates looks a little bit like the following:

myList.forEach (new Closure(this) {
    void doCall(Object s) {
        println s
    }
}

This creates an anonymous class derived from groovy.lang.Closure that does not implement any specific interface. Nevertheless, it can be used as parameter here. This is possible because Groovy generates a dynamic proxy object at runtime, implementing the ´Consumer´ interface and forwarding any calls to the generated Closure instance.

As a consequence, you can replace Java 8 lambdas by Groovy closures, but not the other way round. When you want to use a Groovy API in Java 8 code, you cannot call a method expecting a Closure with a lambda expression. Closure isn't a functional interface but an abstract class, and that can simply not be implemented by a lambda expression.

8
  • 10
    In Java, you can also omit the round brace for a single lambda parameter: s -> System.out.println(s) so it looks even more like in Groovy. Further, the Java compiler does not create a Consumer implementation it creates only a method holding the code of the lambda. The Consumer implementation invoking that method is generated at runtime. That’s the big advantage of Java lambda over other approaches (like the old inner classes), you don’t have tons of .class files flying around. If you use a method reference instead, System.out::println, there won’t be even a method generated.
    – Holger
    Aug 29, 2014 at 11:15
  • @Holger in C# you can write myList.forEach(System.out.println). Is it possible in Java? Not a Java developer, just asking.
    – nawfal
    Jul 1, 2015 at 11:17
  • @nawfal: the Java syntax is myList.forEach(System.out::println). It’s because System.out is an expression which evaluates to a PrintStream instance and ::println is a method reference pointing to an instance method named println within PrintStream.
    – Holger
    Jul 1, 2015 at 11:22
  • 1
    @nawfal: that does even work with parameters, e.g. Foo::new instead of (x,y)->new Fo(x,y) and with arrays, so the stream API allows something like: Foo[] array =myList.stream().toArray(Foo[]::new);. Even more fancy, within an instance method, you can bind a super-invocation to a function, e.g. list.forEach(super::doSometing); to call a superclass method for each element…
    – Holger
    Jul 1, 2015 at 11:34
  • 1
    @Holger Wow that looks cool. Regarding the super invocation, it's easily there in C#, for eg list.forEach(doSometing) or list.forEach(base.doSometing)
    – nawfal
    Jul 1, 2015 at 11:50
6

Java's lambdas are closures as well. These are the same feature on an abstract level, but in detail and depending on exact version, Groovy may just be creating ad-hoc implementing classes, whereas Java 8 specifies a complete mechanism, consisting of lambda Metafactory, lambda factory, and a mechanism involving invokedynamic to acquire the lambda Metafactory.

1

I wanted a simple local closure to pass / execute. I never found this answer anywhere, so adding my spin, so you can see actual mapping from local groovy closure to local java lambda.

Groovy:

def clos = {name -> sayHello(name)} 
clos('John Doe')

Java:

Consumer<String> clos = name -> sayHello(name);
clos.accept("John Doe");

The key being that bloody Consumer interface with accept() method to invoke - you must match the params and return type of your Java lambda based on their pre-canned Function interfaces (java.util.function.*). That bit is a drag, compared to untyped Groovy version.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.