In Kotlin, there are three return and jump statements:
- return returns from the nearest enclosing or anonymous function;
- break jumps out of the nearest closed loop;
- continue Continue to execute the next step of the most recent closed loop;
The above three expressions can also be used as part of other expressions:
val s = person.name ?: return
break and continue labels
Any expression in Kotlin can use a label, and the format of the label is: label name @, for example, abc@, m@, etc. When using tags, we only need to put the tag in front of the expression, generally there is a space distance from the expression:
// 再 i = 10 时跳出整个循环
loop@ for (i in 1..100) {
for (j in 1..10) {
if (i == 10) break@loop else println("$i : $j")
}
}
return using the label
In general, the return in Kotlin has the same effect as the return in java, which ends the nearest closed function:
var ints = arrayListOf<Int>(0 ,1 ,2, 3)
fun foo() {// 并不会打印出任何值
ints.forEach {
if (it == 0) return
print(it)
}
}
However, when return is followed by a label, it means that the expression marked by the label is terminated after the judgment condition is met, similar to the function of break:
var ints = arrayListOf<Int>(0 ,1 ,2, 3)
fun foo() {
ints.forEach lit@ {
if (it == 0) return@lit
print(it)
}
}
lit@ is the label of the following expression. When it == 0, the expression {…} is terminated, and ints.forEach continues to execute, so the printed result is 123
However, more often than not we use anonymous tags with the same tag name as the function in the lambda expression:
fun foo() {
ints.forEach {
if (it == 0) return@forEach
print(it)
}
}
Alternatively, we can also use an anonymous function instead of a lambda expression, so that the function of this return is to terminate the current anonymous function:
fun foo() {
ints.forEach(fun(value: Int) {
if (value == 0) return
print(value)
})
}
When we need to return a value, we can write like this:
return@a 1
This sentence means: the return result of the expression @a is 1, instead of returning a marked expression (@a 1).