https://kotlinlang.org logo
#getting-started
Title
# getting-started
e

evkaky

09/11/2021, 6:49 AM
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

ephemient

09/11/2021, 6:54 AM
repeat(3, block)
block(0); block(1); block(2)
your early
return
prevents
println()
when
it == 0
, but not
1
or
2
e

evkaky

09/11/2021, 6:56 AM
Then is there any way to make a true break inside
repeat
or
forEach
(like we can do in regular loops)?
e

ephemient

09/11/2021, 7:01 AM
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
3 Views