Kotlin:查找无突变循环计数的惯用和声明性方法



如何计算循环在条件下运行的次数,例如:

var count = 0
while (stk.isNotEmpty()) {
stack.pop()
count++
}

但这涉及到暂时的反击和突变。有没有更好的惯用和声明方式,不使用任何临时变量和突变。我可以想出这样的东西,但它确实感觉很hack:

val count = stk.takeWhile { stk.isNotEmpty() }.also { stk.pop() }.count()

Kotlin 标准库不提供您要查找的内容,但您可以自己创建正在搜索的内容:

fun repeatWhile(condition: () -> Boolean, action: () -> Unit): Int {
var count = 0
while (condition()) {
action()
count++
}
return count
}

并像这样使用它:

val stack = Stack<Int>()
stack.push(1)
stack.push(2)
stack.push(3)
val count = repeatWhile({ stack.isNotEmpty() }) {
stack.pop()
}
println(count) // 3

就个人而言,我认为这并不比将 while-loop 和计数器变量暴露给调用站点更好,就像您在问题中所做的那样。

最新更新