0

I know that you can't have non final/effective final variable inside the lambda. if this happen there may be case you are working on outdated version of the object. I figured that the compiler didn't complain about this code where the function parameter may not be final :

Updating the post with full code:

public static void main(String[] args) {
    Object x=new Object();
    x=new Object();// I can reassign x as much as I can
    test(x);
}


  public static void test(Object x) {
// I can't reassign x here, shouldn't it disallow me to use function parameter ?
    List<String> list=new ArrayList<>();
    list.forEach(entry->System.out.println(entry+x)); // x here could be not final why the compiler didn't complain ?
}
Mohammad Karmi
  • 1,403
  • 3
  • 26
  • 42

2 Answers2

4

The answer is in your question: Because x in test is effectively final, because nothing in test assigns to it.

Note that x in test and x in main have no connection to each other whatsoever. At one point in main, you do read the value of main's x and pass that value into test, but it's the value that's passed, not some kind of connection or link to the x variable itself. (Java is a purely pass-by-value language.) There is no ongoing connection between the two xs. They just happen to both contain the same value (an object reference). The fact you can assign to main's x has no bearing on whether you can assign to test's x.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • what happens to `x` inside `test` method after the method is terminated ? local variables should be deleted but in cases of anonymous class it should still be there right ? as it would be used later – Mohammad Karmi Dec 15 '18 at 12:44
  • 3
    @MohammadKarmi - No, the parameter or variable (I'll just say "variable" for simplicity) goes away regardless. That's part of why only final or effectively-final variables can be used in anonymous classes and lambdas, to avoid confusion: It's not really the variable that's being used, it's a *copy* of the variable's value. [More here](https://stackoverflow.com/a/8943134/157247). This isn't really relevant to your question, since the lambda doesn't survive the termination of the method anyway, but if it did, the `x` parameter would still go away, and the lambda would keep a copy of its value. – T.J. Crowder Dec 15 '18 at 12:51
3

Because it is effectively final. A variable or parameter whose value is never changed after it is initialized is effectively final.

Alex
  • 644
  • 4
  • 10