【问题标题】:Continue in a run block in Kotlin在 Kotlin 中继续运行块
【发布时间】:2018-07-17 04:58:06
【问题描述】:

我正在尝试以惯用的方式将以下 Java 代码转换为 Kotlin:

for (Group group : groups) {
    String groupName = group.getName();
    if (groupName == null) {
        warn("Group name is null for group " + group.getId());
        continue;
    }
    ...
}

我尝试了以下

for (group in groups) {
    val groupName = group.name ?: run {
        warn("Group name is null for group ${group.id}!")
        continue
    }
    ...
}

但是这不会编译错误:

'break' 或 'continue' 跳过函数或类边界

所以我的问题是,有没有更好的方法在 Kotlin 中编写这个?

【问题讨论】:

    标签: java loops kotlin continue


    【解决方案1】:

    通常continue 也可以通过::filter 模拟。

    但由于在这种情况下您还需要一个警告,这使得经典的for 成为最佳解决方案。

    但是有一些替代方案。

    groups.filter { group -> when(group.name) {
            null -> {
                warn("Group name is null for group ${group.id}!")
                false
            }
            else -> true
        }.for Each {
            ...
        }
    }
    

    或使用return@forEach。

    但同样,在这种情况下,经典的for 是最好的解决方案

    【讨论】:

      【解决方案2】:

      不用过多修改你的代码,直接使用旧的if

      for (group in groups) {
          val groupName = group.name
      
          if (groupName == null) {
              warn("Group name is null for group ${group.id}!")
              continue
          }
          ...
      }
      

      【讨论】:

        【解决方案3】:

        同样的java代码可以这样实现。

        for (group in groups) {
            val groupName = group.name
            if(groupName == nul){
              warn("Group name is null for group ${group.id}!")
              continue
            }
            ...
        }
        

        但是,您可以通过提供标签继续顶部循环或 Kotlin 中的其他循环。

        loop@ for (i in 1..100) {
            for (j in 1..100) {
                if (...) continue@loop
            }
        }
        

        更新:

        您不能在 lambda 函数中实现 continue。但您也可以使用return。

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

        输出:

        1245 done with explicit label
        

        参考: https://kotlinlang.org/docs/reference/returns.html

        【讨论】:

          【解决方案4】:

          我想我找到了一个非常令人满意且惯用的解决方案:

          groups.forEach { group ->
              val groupName = group.name ?: run {
                  warn("Group name is null for group ${group.id}!")
                  return@forEach
              }
              ...
          }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2019-04-16
            • 2017-06-04
            • 2017-04-29
            • 1970-01-01
            相关资源
            最近更新 更多