Hey guys! I was quite surprised with this code: ``...
# getting-started
e
Hey guys! I was quite surprised with this code:
Copy code
repeat(3) {
   if (it == 0) return@repeat
   println("inside repeat")
}
it prints “inside repeat” twice instead of 0 times Why is that?
e
repeat(3, block)
block(0); block(1); block(2)
your early
return
prevents
println()
when
it == 0
, but not
1
or
2
e
Then is there any way to make a true break inside
repeat
or
forEach
(like we can do in regular loops)?
e
as they're inline functions, you can return to an outer scope:
Copy code
run {
    repeat(3) {
        if (it == 0) return@run
        println("inside repeat")
    }
}
but if that's necessary, IMO you should consider using a normal
for
loop instead.
Copy code
for (i in 0 until 3) {
    if (i == 0) break
    println("inside for")
}
👍 3