Kotlin is trying to enforce fluent iteration, which covers the vast majority of looping constructs. However, I needed a traditional for loop (like java) with an immediately terminating state scope, exit condition that evaluates before loop-body execution, and a post-execution operation (my use case was complicated: I needed to repeat using a dynamic exit condition based on a compression routine and powers of 2). I came up with these general functions:
fun <S> forloop(state: S, condition: (s: S) -> Boolean, postExecution: (s: S) -> Unit, block: (s: S) -> Unit) {
while (condition(state)) {
block(state)
postExecution(state)
}
}
data class SingleIndex(var i: Int)
fun forloop(i: Int, condition: (s: SingleIndex) -> Boolean, postExecution: (s: SingleIndex) -> Unit, block: (s: SingleIndex) -> Unit) {
forloop(SingleIndex(i), condition, postExecution, block)
}
Examples here:
fun main() {
forloop(0, {it.i < 10}, {++it.i}) {
println("forloop test: i=${it.i}")
}
data class State(var i: Int, var j: Int)
forloop(State(0, 1), {it.i < 10}, {++it.i; it.j += it.i}) {
println("forloop test: i=${it.i}, j=${it.j}")
}
}
Although, in compliance with the language philosophy, you should only use this in rare circumstances.