Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy compiler does not accept java 8 Lambdas

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

However , When i write java8 closure in 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 successully :

Person.findAll().stream()  
like image 775
Abdennour TOUMI Avatar asked May 28 '14 08:05

Abdennour TOUMI


People also ask

Does Groovy support lambda?

Groovy compiler does not accept java 8 Lambdas.

How do I use lambda expression in groovy?

The Groovy syntax doesn't support the lambda expressions, but we can rely on closure coersion to use Groovy closures as Java lambda expressions in our code. In the following sample we use the Java Streams API. Instead of lambda expressions for the filter and map methods we use Groovy closures.

Does Java 8 have lambdas?

Lambda Expressions were added in Java 8. A lambda expression is a short block of code which takes in parameters and returns a value. Lambda expressions are similar to methods, but they do not need a name and they can be implemented right in the body of a method.

Does Java 8 support closures?

In effect, java doesn't have closures at all. One may not notice the difference unless they have used real closures in a language that actually supports them.


1 Answers

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

like image 195
tim_yates Avatar answered Sep 28 '22 08:09

tim_yates