有什么办法可以改变Java Lambda捕获的价值 [英] Is there any way to change value captured by Java Lambda

查看:51
本文介绍了有什么办法可以改变Java Lambda捕获的价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

类似的东西:

    Integer value = 3;
    Consumer<Integer> consumer = input -> {
        value = value * 2;
    };
    consumer.accept(100);
    System.out.println(value);

谢谢! [已解决]

    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

也感谢Umer Farooq的回答 从lambda内部修改局部变量

also thanks for Umer Farooq` s answer Modifying local variable from inside lambda

推荐答案

不,那不可能.

JLS 15.27. 2 说:

使用但未在lambda表达式中声明的任何局部变量,形式参数或异常参数必须声明为final或有效地为final(第4.12.4节),否则在尝试使用时会发生编译时错误.

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.

由于在lambda中使用了value,但在lambda之外声明了它,因此它必须是final或有效的final.这意味着您不能多次为其分配一个值.

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.

当然,如果value是可变对象(例如,AtomicInteger),那么您能够对其进行突变. value引用本身将保持不变,但引用的对象将被更改.

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.

这篇关于有什么办法可以改变Java Lambda捕获的价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆