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?
Lambda functions may be implemented as closures, but they are not closures themselves. This really depends on the context in which you use your application and the environment. When you are creating a lambda function that uses non-local variables, it must be implemented as a closure.
A closure in Groovy is an open, anonymous, block of code that can take arguments, return a value and be assigned to a variable. A closure may reference variables declared in its surrounding scope.
A lambda closure is created when a lambda expression references the variables of an enclosing scope (global or local). The rules for doing this are the same as those for inline methods and anonymous classes. Local variables from an enclosing scope that are used within a lambda have to be final .
Closures are the inline-function valued expressions which means that they are the class functions with bounded variables. Closures can be passed to another function as a parameter. A closure gives us access to the outer function from an inner function.
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:
def adder( int i, Closure cl ) {
cl( i )
}
int v = adder( 2 ) { i ->
i + 8
}
assert v == 10
This in Java 8 becomes:
public class Test {
interface MyAdder {
int call( int i ) ;
}
public int adder( int i, MyAdder adder ) {
return adder.call( i ) ;
}
public static void main( String[] args ) {
int v = new Test().adder( 2, (x) -> x + 8 ) ;
System.out.println( v ) ;
}
}
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 as MyObject::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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With