something like this:
Integer value = 3;
Consumer<Integer> consumer = input -> {
value = value * 2;
};
consumer.accept(100);
System.out.println(value);
Thanks! [Solved]
AtomicInteger value = new AtomicInteger(3);
Consumer<Integer> consumer = input -> {
value.getAndAdd(5); // 8
System.out.println(value.get());
};
consumer.accept(100);
System.out.println(value.get()); // 8
also thanks for Umer Farooq` s answer Modifying local variable from inside lambda
So since the Java compiler only allows final or member references to be accessed in a lambda or anonymous inner classes, the answer is no. You can however (as you seem to have found), change the state inside of a final reference.
You found a workaround with
AtomicInteger
, which works in your specific case as you are modifying anInteger
. Placing your reference in a final single value array will work for everything though. It's not very pretty, but if you are usingIntelliJ
it will offer to do this change for you if you try modifying final state in a situation like this.Here is an example:
No, that's not possible.
JLS 15.27.2 says:
Since you use
value
in the lambda, but declare it outside of the lambda, it has to be final or effectively final. That means you can't assign it a value more than once.Of course, if
value
were a mutable object (anAtomicInteger
, for instance), then you would be able to mutate it. Thevalue
reference itself would be unchanged, but the object it references would be changed.