Any expression in Kotlin can be labeled with a label. The format of a label is an identifier followed by an @ sign. For example, ABC @ and _isOK@ are valid labels. We can use the Label tag to control the jump behavior of a return, break, or continue statement. A code example is as follows:

fun main(a) {
    val intArray = intArrayOf(1.2.3.4.5)
    intArray.forEach here@{
        if (it == 3) return@here
        println(it)
    }
}
/ / 1
/ / 2
/ / 4
/ / 5
Copy the code

We added the tag her@ at the beginning of the Lambda expression, which is equivalent to recording the address of the instruction entry of the Lambda expression, and then using return@here inside the expression to jump to that address in the Lambda expression. This makes the code easier to understand.

In addition, you can use implicit tags for more convenience. The label has the same name as the function that receives the Lambda. A code example is as follows:

fun main(a) {
    val intArray = intArrayOf(1.2.3.4.5)
    intArray.forEach {
        if (it == 3) return@forEach
        println(it)
    }
}
/ / 1
/ / 2
/ / 4
/ / 5
Copy the code