Java8在非最终变量上有效地最终编译时错误 [英] Java8 Effectively Final compile time error on non final variable

查看:16
本文介绍了Java8在非最终变量上有效地最终编译时错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将 java8 forEach 循环中的布尔变量更改为非最终的 true.但我收到以下错误:在封闭范围内定义的局部变量必须是最终的或有效的最终变量.

I'm trying to change the boolean variable inside java8 forEach loop to true which is non final. But I'm getting following error : Local variable required defined in an enclosing scope must be final or effectively final.

如何解决这个错误?

代码:

boolean required = false; 

这是我在函数中创建的变量.

This is the variable I have created in the function.

现在当我试图改变它时:

Now when I'm trying to change it :

   map.forEach((key, value) -> {
        System.out.println("Key : " + key + " Value : " + value);
        required = true;
    });

我收到错误:在封闭作用域中定义的局部变量必须是最终的或有效的最终变量.

I'm getting the error : Local variable required defined in an enclosing scope must be final or effectively final.

为什么会出现这个错误以及如何解决?

Why this error is arising and how to resolve it?

推荐答案

您不能从 lambda 表达式的主体更改局部变量.有几种方法可以解决这个问题:

You cannot change the local variable from the body of lambda expression. There are several ways to overcome this:

  • 在这种特殊情况下,您可以只设置 boolean required = !map.isEmpty(); 而无需任何 lambda 表达式.如果你想根据某些条件设置它,你可以使用 Stream API:

  • In this particular case you can just set boolean required = !map.isEmpty(); without any lambda expression. If you want to set it based on some condition, you can use the Stream API:

boolean required = map.entrySet().stream().anyMatch(entry -> ...);

此解决方案是最受欢迎的.

This solution is the most preferred.

required 变量转换为封闭类的字段.

Convert the required variable to the field of the enclosing class.

这篇关于Java8在非最终变量上有效地最终编译时错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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