Kotlin 中“forEach"中的“break"和“continue" [英] `break` and `continue` in `forEach` in Kotlin
问题描述
Kotlin 有非常好的迭代函数,例如 forEach
或 repeat
,但我无法使 break
和 continue
操作符与它们一起工作(本地和非本地):
Kotlin has very nice iterating functions, like forEach
or repeat
, but I am not able to make the break
and continue
operators work with them (both local and non-local):
repeat(5) {
break
}
(1..5).forEach {
continue@forEach
}
我们的目标是用尽可能接近的函数语法来模拟通常的循环.在某些旧版本的 Kotlin 中这绝对是可能的,但我很难重现语法.
The goal is to mimic usual loops with the functional syntax as close as it might be. It was definitely possible in some older versions of Kotlin, but I struggle to reproduce the syntax.
问题可能是标签 (M12) 的错误,但我认为第一个示例应该可以正常工作.
The problem might be a bug with labels (M12), but I think that the first example should work anyway.
在我看来,我曾在某处阅读过有关特殊技巧/注释的内容,但我找不到有关该主题的任何参考资料.可能如下所示:
It seems to me that I've read somewhere about a special trick/annotation, but I could not find any reference on the subject. Might look like the following:
public inline fun repeat(times: Int, @loop body: (Int) -> Unit) {
for (index in 0..times - 1) {
body(index)
}
}
推荐答案
编辑:
根据 Kotlin 的 documentation,可以模拟 continue
使用注释.
Edit:
According to Kotlin's documentation, it is possible to simulate continue
using annotations.
fun foo() {
listOf(1, 2, 3, 4, 5).forEach lit@ {
if (it == 3) return@lit // local return to the caller of the lambda, i.e. the forEach loop
print(it)
}
print(" done with explicit label")
}
如果你想模拟一个break
,只需添加一个run
块
If you want to simulate a break
, just add a run
block
fun foo() {
run lit@ {
listOf(1, 2, 3, 4, 5).forEach {
if (it == 3) return@lit // local return to the caller of the lambda, i.e. the forEach loop
print(it)
}
print(" done with explicit label")
}
}
原答案:
由于您提供了 (Int) ->单元
,你不能打破它,因为编译器不知道它在循环中使用.
Original Answer:
Since you supply a (Int) -> Unit
, you can't break from it, since the compiler do not know that it is used in a loop.
您有几个选择:
使用常规 for 循环:
for (index in 0 until times) {
// your code here
}
如果循环是方法中的最后一段代码
您可以使用 return
退出方法(如果不是 unit
方法,则使用 return value
).
If the loop is the last code in the method
you can use return
to get out of the method (or return value
if it is not unit
method).
使用方法
创建一个自定义重复方法方法,返回 Boolean
以继续.
public inline fun repeatUntil(times: Int, body: (Int) -> Boolean) {
for (index in 0 until times) {
if (!body(index)) break
}
}
这篇关于Kotlin 中“forEach"中的“break"和“continue"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!