4
int count =0;
requestUserDto.getNodeIds().forEach(userNodeId->{
    count++; // this statement shows error
     // some another statements here
    }
});

why count++ shows error

Error:

Local variable i defined in an enclosing scope must be final or effectively final

Cœur
  • 37,241
  • 25
  • 195
  • 267
Arihant Jain
  • 63
  • 1
  • 7
  • Well, as the error message explains, you can't modify a local variable inside a lambda expression. If you'd mention what you are trying to do, perhaps we can suggest an alternative. – Eran May 11 '18 at 06:18
  • 1
    You could potentially use `AtomicInteger` instead, for example. – Jon Skeet May 11 '18 at 06:20
  • thanks But i know the alternative. i want to know why we cant change value here in forEach. In normal for each loop works fine – Arihant Jain May 11 '18 at 06:21
  • You can normally rearrange your code so a variable like that isn't required. – Jacob G. May 11 '18 at 06:34
  • 1
    this is an example not an actual problem. only i want to know why lambdas only allow effectively final variable. – Arihant Jain May 11 '18 at 06:39
  • @ArihantJain, you can simply use an array of `int` to update `arr[0]` in the `for` loop. – mark42inbound May 11 '18 at 06:43
  • @ArihantJain There are good reasons why this limitation of local variables required to be effectively final was designed. [This article](http://www.lambdafaq.org/what-are-the-reasons-for-the-restriction-to-effective-immutability/) gives a fair explanation. – MC Emperor May 11 '18 at 06:47
  • @MCEmperor thanks. this article gives me a clear explanation. – Arihant Jain May 11 '18 at 06:56

1 Answers1

2

Considering lambdas are essentially syntactic sugar for an anonymous inner class, a variable used in a lambda expression must be effectively final. Check out this post for more details.

Ravindra Ranwala
  • 20,744
  • 6
  • 45
  • 63
  • 1
    so that means we can say this is the limitation or drawback of lambdas that used variable is always effectively final. – Arihant Jain May 11 '18 at 06:30
  • 1
    I don't see it as a limitation in lambda since it just substitutes anonymous inner classes where non-final variables can not be defined. The behavior is logically correct. – Ravindra Ranwala May 11 '18 at 06:48
  • 1
    @ArihantJain, such behavior is due to **how closures are handled in Java language**. There's an answer by Jon Skeet [here](https://stackoverflow.com/questions/4732544/why-are-only-final-variables-accessible-in-anonymous-class/4732617) – mark42inbound May 11 '18 at 06:51