Is Java Lambda expression is similar logic of Groovy closure?

前端 未结 3 1764
旧时难觅i
旧时难觅i 2021-02-05 19:06

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

public class LambdaHel         


        
3条回答
  •  长情又很酷
    2021-02-05 19:18

    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 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.

提交回复
热议问题