0

When I try to increment "e" in lambda expression, it gives me an "Variable used in lambda expression should be final or effectively final" error. Here is the code:

int e = 0;
new Thread(() -> {
    e++;
});

Please help me. Thank you

nquantum
  • 11
  • 4
  • How I can fix it tho? I saw someones code that has 1:1 this code and it doesnt error. – nquantum Jan 16 '22 at 19:12
  • 2
    "*I saw someones code that has 1:1 this code and it doesnt error*" that is very unlikely. Please double-check it and provide link to that resource. You could see *similar* code where lamba/local/anonymous class can use local variable to change some *property* of object (like `person.setName("Adam");`) held by variable, but it can't *reassign* new value to local variable. – Pshemo Jan 16 '22 at 19:15
  • 1
    Also see: https://www.baeldung.com/java-effectively-final – Shawn Jan 16 '22 at 19:16
  • There are few ways around it, but picking proper solution would require more information about what you are trying to do. For instance instead of `int` you could use `AtomicInteger` which provides *methods* to modify/read its *state* (integer value). – Pshemo Jan 16 '22 at 19:22

0 Answers0