Does Java 8 Support Closures?

前端 未结 4 1350
野性不改
野性不改 2020-12-04 15:38

I\'m confused. I thought Java 8 was going to emerge from the stone age and start supporting lambdas/closures. But when I try this:

public static void main(St         


        
4条回答
  •  無奈伤痛
    2020-12-04 15:51

    You can use final references to get around altering state of variables declared in an outer scope, but the result remains the same, the state of the closures outer scope is not kept and further alterations to the object referenced to (by a final reference) are seen in the closure.

    @Test
    public void clojureStateSnapshotTest() {
        Function wrapperFunc;
        wrapperFunc = (a) -> {
            // final reference
            final WrapLong outerScopeState = new WrapLong();
    
            outerScopeState.aLong = System.currentTimeMillis();
            System.out.println("outer scope state BEFORE: " + outerScopeState.aLong);
    
            Function closure = (b) -> {
                System.out.println("closure: " + outerScopeState.aLong);
                return b;
            };
    
            outerScopeState.aLong = System.currentTimeMillis();
            System.out.println("outer scope state AFTER: " + outerScopeState.aLong);
    
            // show correct snapshot state
            closure.apply(new Object());
    
            return a;
        };
        // init clojure
        wrapperFunc.apply(new Object());
    }
    
    public class WrapLong {
        public long aLong = 0;
    }
    

    but still fun...

提交回复
热议问题