closures in groovy vs closures in java 8 (lambda expressions)?

后端 未结 2 1855
你的背包
你的背包 2021-02-13 11:41

Given doSomething(Function foo) { println foo(2) }

Groovy: doSomething( { it*it } as Function )

Java: doSomething( (x) -> x*x

2条回答
  •  一生所求
    2021-02-13 12:20

    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 ;-)

提交回复
热议问题