问题描述
:
根据 Kotlin
的文档,可以continue
使用注释进行模拟。
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")
}
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")
}
}
:
既然你提供了 a (Int) -> Unit
,你就不能摆脱它,因为编译器不知道它是在循环中使用的。
你有几个选择:
for (index in 0 until times) {
// your code here
}
您可以使用return
它来退出该方法(或者return value
如果它不是unit
方法)。
创建一个自定义的重复方法方法,该方法返回Boolean
以继续。
public inline fun repeatUntil(times: Int, body: (Int) -> Boolean) {
for (index in 0 until times) {
if (!body(index)) break
}
}
解决方法
Kotlin 有非常好的迭代函数,比如forEach
or
repeat
,但我无法让break
andcontinue
运算符与它们一起工作(本地和非本地):
repeat(5) {
break
}
(1..5).forEach {
continue@forEach
}
目标是用尽可能接近的函数语法来模拟通常的循环。在某些旧版本的 Kotlin 中绝对可以,但我很难重现语法。
问题可能是标签(M12)的错误,但我认为第一个示例无论如何都应该有效。
在我看来,我在某处读过一个特殊的技巧/注释,但我找不到关于这个主题的任何参考资料。可能如下所示:
public inline fun repeat(times: Int,@loop body: (Int) -> Unit) {
for (index in 0..times - 1) {
body(index)
}
}