代码之家  ›  专栏  ›  技术社区  ›  idunnololz adsion

在Kotlin的运行块中继续

  •  2
  • idunnololz adsion  · 技术社区  · 6 年前

    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写这个?

    4 回复  |  直到 6 年前
        1
  •  1
  •   elect    6 年前

    正常地 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 .

    但再一次,在这种情况下,一个经典 是最好的解决方案

        2
  •  0
  •   guenhter    6 年前

    在不太修改代码的情况下,只需使用旧代码即可 if

    for (group in groups) {
        val groupName = group.name
    
        if (groupName == null) {
            warn("Group name is null for group ${group.id}!")
            continue
        }
        ...
    }
    
        3
  •  0
  •   Bhuvanesh BS    6 年前

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

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

    科特林 通过给标签。

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

    更新:

    你无法实现 continue 在lambda函数中。但你可以使用 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
  •  0
  •   idunnololz adsion    6 年前

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

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