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.