https://kotlinlang.org logo
#language-proposals
Title
# language-proposals
b

Ben Woodworth

10/25/2023, 7:43 AM
Has there been any consideration for
break
and
continue
as operator functions, for use in loop-like functions? I'm imagining the compiler seeing that the operators present in scope, allowing break/continue, and compile down to a return to end the current block early, then call the operator functions to let the loop-like function know to handle it. It'd be useful in stdlib functions like forEach, and for me, a parameterized loop library I'm working on (here). I'm picturing something like this:
Copy code
class LoopScope {
    internal var shouldBreak = false

    operator fun onBreak() {
        shouldBreak = true
    }

    operator fun onContinue() {
        // no handling needed, the compiler just inserts a return in the current scope
    }
}

fun loop(block: LoopScope.() -> Unit) {
    val scope = LoopScope()

    do {
        scope.block()
    } while (!scope.shouldBreak)
}
s

Sam

10/25/2023, 8:24 AM
Sounds like you could add this use case to https://youtrack.jetbrains.com/issue/KT-19748
👍 1