【问题标题】:How to continue logic in for-each? [duplicate]如何在 for-each 中继续逻辑? [复制]
【发布时间】:2018-12-23 04:49:04
【问题描述】:

我可以在正常的 for 循环中使用continue

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
}

有没有办法为forEach 使用类似的continue 语句?

【问题讨论】:

    标签: kotlin


    【解决方案1】:

    来自forEach的源代码:

    @kotlin.internal.HidesMembers
    public inline fun <T> Iterable<T>.forEach(action: (T) -> Unit): Unit {
        for (element in this) action(element)
    }
    

    对于集合的每个元素,都会应用一个 lambda 方法 action。因此,为了进入for loop 中的下一个元素,lambda 方法必须完成。并完成它return 但必须在@forEach 范围内调用:

    (0 .. 10).forEach {
        // .. some initial code
        if (i = something) {
            return@forEach
        }
        // .. some other code
    }
    

    【讨论】:

      【解决方案2】:

      使用return@forEach 而不是continue

      【讨论】:

      • 应该是return@forEach
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-27
      • 2019-07-10
      • 2013-06-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-24
      相关资源
      最近更新 更多