Kotlin minimalist tutorial (7) - return and jump

Return and jump

Kotlin has three structured jump expressions:
-return by default, it is returned from the function or anonymous function that most directly surrounds it
-break terminates the loop that most directly surrounds it
-continue to the next cycle that most directly surrounds it

Any expression in Kotlin can be marked with a label in the form of an identifier followed by an @ symbol. For example, abc @, fooBar @ are valid labels

fun main(args: Array<String>) {
    fun1()
}

fun fun1() {
    val list = listOf(1, 4, 6, 8, 12, 23, 40)
    loop@ for (it in list) {
        if (it == 8) {
            continue
        }
        if (it == 23) {
            break@loop
        }
        println("value is $it")
    }
    println("function end")
}
value is 1
value is 4
value is 6
value is 12
function end

Kotlin has functions, local functions and object expressions. So kotlin's functions can be nested
The return of the tag restriction allows us to return from an outer function. The most important purpose is to return from a lambda expression
. It is usually more convenient to use an implicit label with the same name as the function that accepts the lambda

fun main(args: Array<String>) {
    fun1()
    println("-------------")
    fun2()
    println("-------------")
    fun3()
    println("-------------")
    fun4()
}

fun fun1() {
    val list = listOf(1, 4, 6, 8, 12, 23, 40)
    list.forEach {
        if (it == 8) {
            return
        }
        println("value is $it")
    }
    println("function end")
}

fun fun2() {
    val list = listOf(1, 4, 6, 8, 12, 23, 40)
    list.forEach {
        if (it == 8) {
            return@fun2
        }
        println("value is $it")
    }
    println("function end")
}

//The local return used in fun3() and fun4() is similar to using continue in a regular loop
fun fun3() {
    val list = listOf(1, 4, 6, 8, 12, 23, 40)
    list.forEach {
        if (it == 8) {
            return@forEach
        }
        println("value is $it")
    }
    println("function end")
}

fun fun4() {
    val list = listOf(1, 4, 6, 8, 12, 23, 40)
    list.forEach loop@ {
        if (it == 8) {
            return@loop
        }
        println("value is $it")
    }
    println("function end")
}
value is 1
value is 4
value is 6
-------------
value is 1
value is 4
value is 6
-------------
value is 1
value is 4
value is 6
value is 12
value is 23
value is 40
function end
-------------
value is 1
value is 4
value is 6
value is 12
value is 23
value is 40
function end

Keywords: Lambda

Added by digioz on Tue, 31 Mar 2020 16:58:50 +0300