foreach - 在 kotlin 中返回/突破无限 foreach

标签 foreach kotlin return infinite

对于类,我必须制作一个计算生日问题的程序
现在我正在尝试同时学习 kotlin,但在使用一小段代码时遇到了麻烦:

        val checkSet = mutableSetOf<Int>()
        generateSequence{ Random.nextInt(n)}.forEach {
            if(!checkSet.add(it)) {
                return@outForeach
            }
        }
        outForeach@
        sum += checkSet.size

正如你所看到的,我试图用一个无限序列来做到这一点。 Kotlin 不接受这一点,因为 outForeach 是一个 Unresolved 引用。但这也不起作用:
        val checkSet = mutableSetOf<Int>()
        generateSequence{ Random.nextInt(n)}.forEach {
            if(!checkSet.add(it)) {
                return@forEach
            }
        }
        sum += checkSet.size

这将再次启动 forEach 循环。有没有办法将某些东西实现为 forEachUntil 左右?

附言我知道这看起来很像这个问题:'return' doesn't jump out of forEach in Kotlin只是我没有真正得到答案,我不知道它是否适用于此。还有一种实现 forEachUntil 的方法对我来说似乎要优雅得多

最佳答案

您可能要考虑的替代方案而不是 first :

  • 使用一个简单的 while 没有主体:
    while (checkSet.add(Random.nextInt(n))); // <- that semicolon is required! otherwise you execute what is coming next within the while
    
  • 使用带有标签的 run :
    run outForeach@{
      generateSequence{ Random.nextInt(n)}.forEach {
        if(!checkSet.add(it)) {
          return@outForeach
        }
      }
    }
    
  • 也许 takeWhile 也可能有帮助。然而,在这种特定情况下,它肯定不是(因为它会检查 checkSet 并为我们留下一个未被消耗的序列......但如果条件不同,考虑像 take takeWhile , takeLast 等):
    generateSequence { Random.nextInt(n) }
        .takeWhile(checkSet::add) // as said: for this specific condition it doesn't make sense... 
        .forEach { /* do nothing except consume the sequence */ } // the same values you added to the set would be available in this step of course
    
  • 关于foreach - 在 kotlin 中返回/突破无限 foreach,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53744422/

    相关文章:

    php - 使用多个数组时仅插入第一行数据

    android - 使用 Kotlin 将运行时边距设置为任何 View

    Java - 无法摆脱这种递归方法

    java - 如何在 Kotlin 中压缩列表并跳过下一个?

    Python - 从其他类中的方法检索值

    c++ - 为什么不能在返回语句中使用 "<<"运算符?

    java - 通过Java中的for-each循环检测第一次迭代

    c# - InvalidCastException : Cannot cast from source type to destination type.(Unity c#,foreach 列表循环)

    php - 如何检查变量是否为数组?...或类似数组的东西

    java - Android Studio 3.0 金丝雀 1 : Kotlin tests or Java tests referring to Kotlin classes fail