0

I am curious why the following code is valid (for sure not best practice), because I always thought a variable in this case (order) within a lambda needs to be final or at least is effective final. So how is it possible to increase the order value for each ref? The ref contains increasing numbers 0, 10, 20, ...

public class A {

  private int order = 0;

  public void addOrder() {
    this.order = 0;
    getRefsSomewhere().stream().forEach(ref -> updateRef(ref, order+=10));
  }
}

If I just change it slightly it doesn't compile anymore (as expected)

public class A {
  public void addOrder() {
    int order = 0;
    getRefsSomewhere().stream().forEach(ref -> updateRef(ref, order+=10));
  }
}

Any pointers why the first example works?

Christian
  • 1,664
  • 1
  • 23
  • 43

0 Answers0