Kotlin 之 forEach 跳出循环
Java 代码中跳出 for 循环我们都用 break,continue关键字。
kotlin 中有些 for 循环的写法 break,continue 关键字并不好用。
for(xxx in yyy) {}
for (int i in list) {
if (i == 1) {
continue
}
if(i == 2) {
break
}
}
这种 for (xxx in yyy) 的写法可以直接使用 break, continue 关键字。
但是 xxx.forEach() 这种写法,编译器无法识别 break, continue 关键字了。需要使用其他招式。
return@forEach
(0..10).forEachIndexed { index, it ->
println("-- forEach -- ${index} --")
if (it > 5) return@forEachIndexed
println(it)
}
输出结果:
-- forEach -- 0 --
0
-- forEach -- 1 --
1
-- forEach -- 2 --
2
-- forEach -- 3 --
3
-- forEach -- 4 --
4
-- forEach -- 5 --
5
-- forEach -- 6 --
-- forEach -- 7 --
-- forEach -- 8 --
-- forEach -- 9 --
-- forEach