Java8 Stream编译器消息-局部变量必须是final或有效的final [英] Java8 Stream compiler message -- local variable must be final or effectively final

查看:769
本文介绍了Java8 Stream编译器消息-局部变量必须是final或有效的final的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个小问题.当我编写此for循环时,f.getAnswerScore().get(i)....中的变量i用错误消息加下划线:-我在封闭范围内定义的局部变量必须是final或 有效地最终.这与流有关吗?也许不能在循环中使用流?

I have a little problem. When I write this for loop, the variable i in f.getAnswerScore().get(i).... is underlined with error message : - Local variable i defined in an enclosing scope must be final or effectively final. Does this have something to do with streams? Maybe streams can't be used in loops?

for (int i = 0; i < 10; i++) {
    correct = active.stream()
        .filter(f -> f.getAnswerScore().get(i).getStatus().equals(AnswerStatus.ANSWERED_CORRECT))
        .count();
}

推荐答案

就像匿名内部类一样,lambda表达式只能访问局部变量,如果它们是final或有效最终"变量,则它们只能访问局部变量. (Java 8或更高版本;不是final,但一旦分配就永远不会更改.)

Like anonymous inner classes, lambda expressions can only access local variables if they are final or "effectively final" (Java 8 or higher; not final but never changed once assigned).

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主体中使用但未声明的局部变量必须在lambda主体之前进行明确赋值(第16节(确定赋值)),否则会发生编译时错误.

Any local variable used but not declared in a lambda body must be definitely assigned (§16 (Definite Assignment)) before the lambda body, or a compile-time error occurs.

关于变量使用的类似规则适用于内部类的主体(第8.1.3节).对有效最终变量的限制禁止访问动态变化的局部变量,因为局部变量的捕获可能会引入并发问题.与最终限制相比,它减轻了程序员的文书负担.

Similar rules on variable use apply in the body of an inner class (§8.1.3). The restriction to effectively final variables prohibits access to dynamically-changing local variables, whose capture would likely introduce concurrency problems. Compared to the final restriction, it reduces the clerical burden on programmers.

声明一个等于ifinal变量并使用它.

Declare a final variable equal to i and use it.

for(int i = 0; i< 10; i++){
     final int j = i;
     correct = active
         .stream()
         .filter(f-> f.getAnswerScore().get(j).getStatus().equals(AnswerStatus.ANSWERED_CORRECT))
         .count();
}

这篇关于Java8 Stream编译器消息-局部变量必须是final或有效的final的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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