Kotlin 之 forEach 跳出循环

本文介绍了在Kotlin中,如何在`forEach`循环中实现跳出循环。与Java不同,Kotlin的`forEach`不支持直接使用`break`或`continue`关键字。文章通过示例展示了使用`return@forEach`来达到跳出循环的效果,并提供了其他相关示例。
摘要由CSDN通过智能技术生成

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 
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值