Is there any way to change value captured by Java

2019-08-01 03:44发布

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

标签: java lambda
2条回答
来,给爷笑一个
2楼-- · 2019-08-01 03:59

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 an Integer. Placing your reference in a final single value array will work for everything though. It's not very pretty, but if you are using IntelliJ it will offer to do this change for you if you try modifying final state in a situation like this.

Here is an example:

final int[] value = { 3 };
Consumer<Integer> consumer = input -> {
    value[0] = value[0] * 2;
};
consumer.accept(100);
System.out.println(value[0]);
查看更多
Deceive 欺骗
3楼-- · 2019-08-01 04:03

No, that's not possible.

JLS 15.27.2 says:

Any local variable, formal parameter, or exception parameter used but not declared in a lambda expression must either be declared final or be effectively final (§4.12.4), or a compile-time error occurs where the use is attempted.

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 (an AtomicInteger, for instance), then you would be able to mutate it. The value reference itself would be unchanged, but the object it references would be changed.

查看更多
登录 后发表回答