javagroovyjava-8closures

Groovy compiler does not accept Java 8 lambdas


As we know, the Groovy syntax accepts closures. Today also, Java 8 adds in its syntax closure.

However, when I write a Java 8 closure in a Groovy file, I get an error like the following:

Person.findAll().stream().filter(e-> e.age > 20)

We get this error:

org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
Script1.groovy: 7: unexpected token: -> @ line 7, column 39.
   Person.findAll().stream().filter(e-> e.controllerId > 0)
                                         ^

1 error

Nevertheless, the following works successfully:

Person.findAll().stream()  

Solution

  • Yeah, the Groovy parser does not accept Java 8 Lambdas (not closures).

    You can use a closure in place of it (assuming you're on Groovy 2.3.*)

    ie:

    Person.findAll().stream().filter( { e -> e.age > 20 } )
    

    edit:

    Groovy 3.0+ will accept lambda format