对于类,我必须制作一个计算生日问题的程序
现在我正在尝试同时学习 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/