Kotlin有非常好的迭代函数,比如forEachrepeat,但我无法让breakcontinue运算符与它们一起工作(本地和非本地):

repeat(5) {
    break
}

(1..5).forEach {
    continue@forEach
}

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)的错误,但我认为第一个示例应该可以工作.

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)
    }
}

推荐答案

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")
}

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")
    }
}

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.

You have few options:

Use a regular for loop:

for (index in 0 until times) {
    // your code here
}

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).

Use a method
Create a custom repeat method method that returns Boolean for continuing.

public inline fun repeatUntil(times: Int, body: (Int) -> Boolean) {
    for (index in 0 until times) {
        if (!body(index)) break
    }
}

Kotlin相关问答推荐

Lambda和普通Kotlin函数有什么区别?

在Kotlin中求n个ClosedRange实例相交的最常用方法是什么?

如果启用了Flyway迁移,则不能具有配置属性';datources.default.架构-生成

相当于roomdb中的DateTime Bigint列的是什么

如何检测一个值是否是Kotlin中的枚举实例?

使函数同时挂起和取消挂起

collectAsState 未从存储库接收更改

Kotlin 中的密封和内部有什么区别?

在 Kotlin 中,我可以在集合上有一个条件构建器元素吗?

使用 Compose for Desktop Bundle 文件

如何在 Kotlin 中实现 Composition UML 关系?

Kotlin RxJava 可空的错误

参考 Kotlin 中的 Java 接口静态字段

调用单元测试验证伴随对象方法

kotlin-bom 库是做什么的?

在Kotlin中传递并使用函数作为构造函数参数

main函数和常规函数有什么区别?

如果作为 RxJava Observable 提供,Kotlin 密封类子类需要强制转换为基类

Dagger +Kotlin 不注入

Android Compose 生产准备好了吗?