当前位置:网站首页>Kotlin 正确退出 foreach、foreachIndexed 循环函数
Kotlin 正确退出 foreach、foreachIndexed 循环函数
2022-07-16 18:08:00 【匆忙拥挤repeat】
问题现象
(1..8).forEach {
if (it % 2 == 0) {
return@forEach
}
println("forEach: $it")
}
如上的 return 语句,并没有 return 整个循环。
输出:
forEach: 1
forEach: 3
forEach: 5
forEach: 7
相当于,仅是个类似 continue 的作用。
而在 foreach、foreachIndexed 循环函数 中,无法使用 continue 和 break 关键字。
加标签 [email protected] 尝试解决
(1..8).forEach [email protected]{
if (it % 2 == 0) {
return@fe
}
println("forEach: $it")
}
加了标签 [email protected] 后,也并没有改变输出结果。这里的加标签,只是对默认的函数名 [email protected] 的重命名
解决方案,增加一个外部函数作用域
增加一个外部函数作用域:
(1..8).also {
range ->
range.forEach [email protected]{
if (it % 2 == 0) {
return@also
}
println("forEach: $it")
}
}
[email protected] 退出了整个 also {}。
输出:
forEach: 1
可以对 also { } 取别名标签。 eg. (1…8).also [email protected] { … }
当然选择其它的标准函数 (also、let、run、apply、with) 作外部函数,都可以。
with (1..8) {
this.forEach [email protected]{
if (it % 2 == 0) {
return@with
}
println("forEach: $it")
}
}
边栏推荐
- Why should V-for add key
- 【uniapp调用微信支付】uniapp开发小程序-调用微信支付
- Fade in and fade out 1920-500 (8)
- OpenGL es learning (6) -- recognizing textures
- Research on driverless dynamic obstacle avoidance strategy | robot dynamic obstacle avoidance strategy
- Paddle CrowdNet 人群密度估计
- 程序员都看不懂的代码
- Theoretical knowledge of static routing
- 市场监管总局:小布丁雪糕等15批次雪糕产品不合格
- pytorch LSTM 文本分类简单例子
猜你喜欢

【学浪下载教程】03学浪下载之Proxifier设置

go ———数组与切片的区别

【学浪下载教程】01学浪下载之Fiddler的配置

v-for为什么要加key

Research on driverless dynamic obstacle avoidance strategy | robot dynamic obstacle avoidance strategy

Theoretical knowledge of static routing

无人驾驶动态避障策略调研 | 机器人动态避障策略

Improvement 20 of yolov5: introduction of new neural network operator into network

Redis-Cluster集群、

Pytorch 深度可分离卷积和MobileNet_v1
随机推荐
Unity-2D像素晶格化消融
Applet page navigation
netstat常用场景记录
[Xuelang download tutorial] 06 Xuelang simulated web version login, without client and global agent software
World Tour Finals 2019 D - special boxes
自定义类型详解(c语言)
A down jacket live broadcast Gmv soared by 430%. Is this the secret of off-season hot sales?
Remember these points and you can quickly find bugs
Code of solidity
20. Network principles - Basic Concepts
Dialogue Yinqi: what we insist on will not change, and broad vision will jump out of the "cyclical law" of enterprise scientific research
静态路由理论知识
【学浪下载教程】06学浪模拟网页版登录,无需客户端和全局代理软件
1.解决com.mysql.jdbc.PacketTooBigException: Packet for query is too large
Daily question · sword finger offer | 041 Average value of sliding window (same as 346) · queue
The cause of low code Trilogy
Feign call delivery request header
21. How does the program execute after entering the URL in the browser?
R语言ggplot2可视化:ggplot2可视化密度图(density plot)并使用geom_vline函数添加均值竖线、添加均值数值标签(Mean Line or Vertical Line )
Termux related