kotlin - 如何在 for-each 中继续逻辑?
问题描述
我可以continue
在正常的 for 循环中使用。
for (i in 0..10) {
// .. some initial code
if (i == something) continue
// .. some other code
}
但是好像不能用forEach
(0 .. 10).forEach {
// .. some initial code
if (i == something) continue
// .. some other code
}
有没有办法使用类似的continue
声明forEach
?
解决方案
从源代码forEach
:
@kotlin.internal.HidesMembers
public inline fun <T> Iterable<T>.forEach(action: (T) -> Unit): Unit {
for (element in this) action(element)
}
对于集合的每个元素,action
都会应用一个 lambda 方法。因此,为了进入for loop
lambda 方法中的下一个元素,必须完成。并完成它,但必须return
在范围内调用:@forEach
(0 .. 10).forEach {
// .. some initial code
if (i = something) {
return@forEach
}
// .. some other code
}
推荐阅读
- reactjs - TypeError:无法读取未定义的 mapStateToProps 的属性
- javascript - 在 Angular 应用程序中全局使用 ngx-toastr
- c# - 从 C# 运行 PowerShell 脚本时 Add-PSSnapin 的路径不正确
- javascript - 将 highcharts / stockchart 导出为图像与 Web 浏览器中的不同
- python - 如何在另一个模型中从 django 用户获取特定用户
- hibernate - JPA:尝试从双向多对多关系中删除实体
- c++ - 如何找到模板函数返回的类型
- android - 在 RecyclerView 中为 ImageView 设置动画的函数
- java - 让按钮在列表视图中工作
- c++ - 如何让 TTS 立即停止说话?