Given doSomething(Function foo) { println foo(2) }
Groovy: doSomething( { it*it } as Function )
Java: doSomething( (x) -> x*x )
Is there any difference between the two?
Given doSomething(Function foo) { println foo(2) }
Groovy: doSomething( { it*it } as Function )
Java: doSomething( (x) -> x*x )
Is there any difference between the two?
In Groovy, closures are first class citizens of type
groovy.lang.Closure
, whereas lambdas in Java 8 are actual instances of the default method interface they represent.This means you need to use the
as
keyword in Groovy (as you've shown), but alternatively, in Java you need to specify an interface, so in Groovy, you could do:This in Java 8 becomes:
Obviously, you can also now declare default implementation in interfaces, which I didn't show here...
Not sure if this is all the differences, but it's a difference at least ;-)
{() -> new MyObject();}
it can be written asMyObject::new
. I think not all lambda expressions can be represented by using Method References.I dont think it would be ideal to compare the lambda expression support in Java 8 with that of more mature Groovy or Scala support. This is the first step for Java to introduce lambda expressions so going forward we can expect to have more mature support for lambda expressions.