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