在Kotlin的`forEach`中`break`和`continue` [英] `break` and `continue` in `forEach` in Kotlin

查看:661
本文介绍了在Kotlin的`forEach`中`break`和`continue`的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Kotlin有很好的迭代函数,比如 forEach 或者 repeat ,但是我不能使 break continue 操作符与它们一起工作(包括本地和非本地):

  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)
}
}
旧文档,应该可以使用注释。但是,它还没有实现。


断开并继续执行自定义控制结构
yet


问题这个功能是3岁,所以我想这是不会被固定的。






原始回答

由于您提供了(Int) - >单元,你不能打破它,因为编译器不知道它在循环中使用。





使用常规循环:

  // your code here 
}

如果循环是方法的最后一个代码

,可以使用 return 来退出方法(或返回值,如果它不是 unit 方法)。

使用方法

创建一个返回 Boolean 继续的自定义重复方法方法。


  public inline fun repeatUntil(times:Int,body:(Int) - > Boolean){
for如果(!body(index))break
}
}

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
}

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.

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

解决方案

Edit:
According to Kotlin's old documents, it should be possible using annotations. However, it is not implemented yet.

Break and continue for custom control structures are not implemented yet

The issue for this functionality is 3 years old, so I guess it is not going to be fixed.


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..times - 1) {
    // 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..times - 1) {
        if (!body(index)) break
    }
}

这篇关于在Kotlin的`forEach`中`break`和`continue`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆