Kor*_*gay 3 java label for-loop java-8
编译后没有任何错误:
class App {
boolean b;
boolean c;
void foo(List<Integer> ints) {
myLabel:
for (Integer i : ints) {
while (!b) {
if (c) {
continue myLabel;
}
}
};
}
}
Run Code Online (Sandbox Code Playgroud)
但如果我修改foo如下:
void foo(List<Integer> ints) {
myLabel:
ints.forEach(integer -> {
while (!b) {
if (c) {
continue myLabel;
}
}
});
}
Run Code Online (Sandbox Code Playgroud)
我明白了 Error:(17, 21) undefined label: myLabel
有什么不同?据我所知,新增forEach只是增强for循环的捷径?
正如评论中所述,forEach只是一个方法调用.片段
myLabel: ints.forEach(integer -> ...);
Run Code Online (Sandbox Code Playgroud)
是一个带标签的声明:
标识符语句标签与标签语句中出现的任何地方使用
break或continue声明(§14.15,§14.16).
重复一下,带标签的语句是方法调用表达式.您的continue陈述不在标签声明范围内.
你的continue说法是内whilelambda表达式的身体中出现的语句.
continue带有标签的语句Identifier尝试将控制权转移到Identifier与其标签相同的封闭标签声明(第14.7节) ; 该语句称为继续目标,然后立即结束当前迭代并开始新的迭代.[...]
continue目标必须是a
while,do或for语句,否则会发生编译时错误.一个
continue语句必须引用一个标签的立即封闭方法,构造函数初始化,或lambda体内.没有非本地跳跃.如果Identifier在紧密封闭的方法,构造函数,初始化程序或lambda主体中没有标记语句作为其标签包含continue语句,则会发生编译时错误.
由于在紧邻的lambda体中没有标记的带有标记的(while,do或for)语句myLabel,因此会出现编译时错误.