Label Reference in Kotlin

This post was originally posted at https://agrawalsuneet.github.io/blogs/label-reference-in-kotlin/ and reposted on Medium on 9th July 2018.
loopi@ for( i in 1..5){
print(i)
}
But what is the use ?
  • break : Terminates the nearest enclosing loop.
  • continue : Proceeds to the next step of the nearest enclosing loop.
  • return : Return from the nearest enclosing function or anonymous function.
for( i in 1..3){
for (j in 5..7){
print ((i * 100) + j)
print(" ")
}

println( i.toString() + " loop ends")
}

println("We are done")
105 106 107 1 loop ends 
205 206 207 2 loop ends
305 306 307 3 loop ends
We are done
105 106 107 1 loop ends 
205
We are done
Let me think
for( i in 1..3){
for (j in 5..7){
if(i == 2 && j == 6) break
print ((i * 100) + j)
print(" ")
}

if(i == 2) break
println( i.toString() + " loop ends")
}

println("We are done")
exactly !!!
loopi@ for( i in 1..3){
for (j in 5..7){
if(i == 2 && j == 6) break@loopi
print ((i * 100) + j)
print(" ")
}
println( i.toString() + " loop ends")
}

println("We are done")
loopi@ for( i in 1..3){
for (j in 5..7){
if(i == 2 && j == 6) continue@loopi
print ((i * 100) + j)
print(" ")
}
println( i.toString() + " loop ends")
}

println("We are done")
105 106 107 1 loop ends 
205
305 306 307 3 loop ends
We are done
fun somefunction() {
listOf(1, 2, 3, 4, 5).forEach {
if (it == 3) return
print(it)
println()
}
println("I will never be printed :( ")
}
1 2
fun somefunction() {
listOf(1, 2, 3, 4, 5).forEach lambda@{
if (it == 3) return@lambda
print(it)
print(" ")
}
println("I'll be printed too :) ")
}
1 2 4 5 I'll be printed too :)
fun somefunction() {
listOf(1, 2, 3, 4, 5).forEach {
if (it == 3) return@forEach
print(it)
print(" ")
}
println("I'll be printed too :) ")
}
fun somefunction() {
listOf(1, 2, 3, 4, 5).forEach(fun(value: Int) {
if (value == 3) return
print(value)
print(" ")
})
print("I'll be printed too :) ")
}
fun somefunction() {
run loop@{
listOf(1, 2, 3, 4, 5).forEach {
if (it == 3) return@loop
print(it)
print(" ")
}
}
print("Now I'll be printed too :) ")
}
1 2 I'll be printed too :)

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store