Search code examples
kotlinfunctional-programmingdeclarative

Kotlin: Idiomatic & Declarative way to find count of a loop without mutation


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()

Solution

  • The Kotlin standard library does not offer what you are looking for, but you could create something you are searching for own your own:

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

    And use it like this:

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

    Personally, I don't think this a better than exposing the while-loop and the counter variable to the call-site, like you did in your question.