I am really confused while using Lambda expression in my code. I have declared a variable outside of the lambda expression and while using it inside the lambda expression, I am getting exception as:
Local variable var1 defined in an enclosing scope must be final or effectively final
Below is my code:
String var1=null;
String var2;
List<String> list = new ArrayList<String>();
list.add("Apple");
list.add("Banana");
list.add("Peach");
list.forEach( (obj) -> { // Outer lambda expression
String var3; //This is declared inside of outerloop but outside of inner loop
list.forEach( (obj2) -> { // Inner lambda expression
var1="With null initialization"; // giving error
var2="Without initialization"; // giving error
var3="var3"; // giving error
});
});
So firstly, how can I remove this error and also declare the variable outside of the lambda expressions?
Secondly:
About var3
, when I remove the declaration of var1
and var2
, the error from var3
disappears which is really strange to me. Why is it giving error when var1
and var2
is declared outside of the scope. How possibly var3
is linked with var1
and var2
.
//String var1=null;
//String var2;
List<String> list = new ArrayList<String>();
list.add("Apple");
list.add("Banana");
list.add("Peach");
list.forEach( (obj) -> { // Outer lambda expression
String var3; //This is declared inside of outerloop but outside of inner loop
list.forEach( (obj2) -> { // Inner lambda expression
var3="var3"; // error is gone when var1 and var2 declaration is removed
});
});