Kotlin Basic Tutorial-return values and jumps

Source: Internet
Author: User
Tags foreach anonymous

Returns and Jumps

Like Java, there are 3 jump statements in Kotlin return break continue break and Continue tags

We can give an alias to any expression, Kotlin call this a label.

Take an example of the previous for Loop statement

Doctorq@for (index in array.indices) {
        println (index)
    }

I've added a label to this for loop, with a suffix of @

doctorq@ for (i-1..100) {
        doctorq2@ for (J-in 1..100) {
            if (i > J) break@doctorq2

            if (i = =) Break@doc Torq
        }
    }

The role of the tag, you can make a jump to the position is very clear, no longer tangled in the nested for loop, there is a jump to where the doubts. You can also choose to jump to any place, more convenient than the Java for loop. the label on return

In some nested functions, you need to return a value to the external function, which requires a label. In particular, it is returned in a lambda expression:

Fun foo () {
    Ints.foreach {
        if (it = = 0) return
        print (IT)
    }
}

The above foreach statement, after encountering 0, will return directly.

If you want to encounter a 0 skip and continue traversing the next element, you cannot use continue at this time.

Fun Foo (array:array<int>) {
    Array.foreach doctorq@{
        if (it = = 0) Return@doctorq
        println (IT)
    }
}

You can also use foreach as the label name

Fun foo () {
    Ints.foreach {
        if (it = = 0) Return@foreach
        print (IT)
    }
}

We can also use anonymous functions instead of lambda expressions, and return returns from anonymous functions to the anonymous function itself.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.