How do I break out of a Kotlin repeat loop?
(I see plenty of answers about forEach, but I want to see a repeat-specific answer.)
- You can't use a naked
return, because that will return from what contains therepeat. - You can't use
break, because:- if the
repeatis inside a loop, you'll break that loop - if the
repeatis not in a loop, you'll get'break' and 'continue' are only allowed inside a loop
- if the
These don't work (they are functionally identical):
repeat(5) { idx ->
println(">> $idx")
if(idx >= 2)
return@repeat // use implicit label
}
repeat(5) @foo{ idx ->
println(">> $idx")
if(idx >= 2)
return@foo // use explicit label
}
In both those cases, you get:
>> 0
>> 1
>> 2
>> 3
>> 4
(The return@ in both those blocks actually acts like a continue, which you can see yourself if you add a println after the if-block.)
So how can I break out of a repeat?