Ben Woodworth
10/25/2023, 7:43 AMbreak
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:
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)
}
Sam
10/25/2023, 8:24 AM