• Any expression in Kotlin may be marked with a label. Labels have the form of an identifier followed by the @ sign, such as abc@ or fooBar@. To label an expression, just add a label in front of it.

    loop@ for (i in 1..100) {
        // ...
    }
  • Use cases,

    • Indicating loop breaks (useful especially when there’s heavy nesting)
    • Non-local return

Indicating loop breaks

loop@ for (i in 1..100) {
    for (j in 1..100) {
        if (...) break@loop
    }
}

Non-local return

fun foo() {
    listOf(1, 2, 3, 4, 5).forEach lit@{
        if (it == 3) return@lit // local return to the caller of the lambda - the forEach loop
        print(it)
    }
    print(" done with explicit label")
}

Better with implicit labels,

fun foo() {
    listOf(1, 2, 3, 4, 5).forEach {
        if (it == 3) return@forEach // local return to the caller of the lambda - the forEach loop
        print(it)
    }
    print(" done with implicit label")
}

Note that such non-local returns are supported only for lambda expressions passed to inline functions. Ref


Refs

  1. https://kotlinlang.org/docs/returns.html#break-and-continue-labels