How to count no.of times a loop has run with a condition, for example:
var count = 0
while (stk.isNotEmpty()) {
stack.pop()
count++
}
But this involves a temporary counter and mutation. Is there a better idiomatic and declarative way without using any temp variable and mutation. I could come-up with something like this, but it does feel hacky:
val count = stk.takeWhile { stk.isNotEmpty() }.also { stk.pop() }.count()
fun main() {
val stk = listOf(1, 2, 5, 70)
//sampleStart
stk.forEachIndexed { index, value ->
println("The value at index $index is $value")
}
//sampleEnd
}
Your code is simple, easy to understand, performant and safe. There is no need to dogmatically complicate things for some ideal/rule/…
The solutions given above:
count(): Move the mutable state to another function. So it is not visible, but works the same way.
fold(...): Adds overhead for the lookup and/or creation of primitive wrappers (at least on the JVM).
Mutable shared state is evil. Immutability is evil, as you can see. Really, you need to find some place where you have mutable state that’s not shared.