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 -- 10 --
run outside@{}
run outside@{
        (0..10).forEachIndexed { index, it ->
            println("-- forEach -- ${index} --")
            if (it > 5) return@outside
            println(it)
        }
    }

输出结果:

-- forEach -- 0 --
0
-- forEach -- 1 --
1
-- forEach -- 2 --
2
-- forEach -- 3 --
3
-- forEach -- 4 --
4
-- forEach -- 5 --
5
-- forEach -- 6 --
another demo :
run outside@{
        videoPath.forEach {
         if ((it <= '\u001f' && it != '\t') || it >= '\u007f') {
              validFlag = false
              return@outside
          }
   }
}
Logo

开源鸿蒙跨平台开发社区汇聚开发者与厂商,共建“一次开发,多端部署”的开源生态,致力于降低跨端开发门槛,推动万物智联创新。

更多推荐