Search code examples
javalambdafinal

Is it possible to use not effectively final or final variable in lambda body or anonymous class?


Is it possible to use variable which is neither not effectively final nor final, in lamba body?
So is there a way to make the following code compile?

class Main {
    interface Test{
        String method();
    }
    void w(){
        String str = "foo";
        str = "bar";
        Test t = () -> str;
    }
}

Solution

  • Yes, it's possible.
    You can copy your value to effectively final local variable:

    class Main {
        interface Test{
            String method();
        }
        void w(){
            String str = "foo";
            str = "bar";
            String tmpStr = str;
            Test t = () -> tmpStr;
        }
    }
    

    Since now your temporary value is effectively final and you can use it in lambda expressions or anonymous classes.