user7153839 user7153839 - 25 days ago 7
Java Question

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

Answer

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.