Kotlin loop control
for loop
The for loop can traverse any object that provides an iterator. The syntax is as follows
for (item in collection) print(item)
The loop body can be a code block
for (item: Int in ints) {
// ……
}
As mentioned above, for can loop through any object that provides an iterator.
If you want to traverse an array or a list by index, you can do this
for (i in array.indices) {
print(array[i])
}
Note that this "traversal on the interval" will be compiled into an optimized implementation without creating additional objects.
Or you can use the library function withIndex
for ((index, value) in array.withIndex()) {
println("the element at $index is $value")
}
Instance
Iterate over the collection
fun main(args: Array<String>) {
val items = listOf("apple", "banana", "kiwi")
for (item in items) {
println(item)
}
for (index in items.indices) {
println("item at $index is ${items[index]}")
}
}
Output result
apple
banana
kiwi
item at 0 is apple
item at 1 is banana
item at 2 is kiwi
while 与 do...while 循环
While is the most basic loop, its structure is
while( 布尔表达式 ) {
//循环内容
}
do...while loop For while statements, if the conditions are not met, you cannot enter the loop. But sometimes we need to execute at least once even if the conditions are not met.
The do...while loop is similar to the while loop, the difference is that the do...while loop will be executed at least once
do {
//代码语句
}while(布尔表达式)
Instance
fun main(args: Array<String>) {
println("----while 使用-----")
var x = 5
while (x > 0) {
println( x--)
}
println("----do...while 使用-----")
var y = 5
do {
println(y--)
} while(y>0)
}
Output result
5
4
3
2
1
----do...while 使用-----
5
4
3
2
1
Return and jump
Kotlin has three structured jump expressions:
- return . By default, it returns from the function that most directly encloses it or the anonymous function.
- break . Terminate the loop that most directly surrounds it.
- continue . Continue to the next cycle that most directly surrounds it.
Kotlin supports traditional break and continue operators in loops
fun main(args: Array<String>) {
for (i in 1..10) {
if (i==3) continue // i 为 3 时跳过当前循环,继续下一次循环
println(i)
if (i>5) break // i 为 6 时 跳出循环
}
}
Output result
1
2
4
5
6
Break and Continue tags
Any expression in Kotlin can be marked with a label. The format of the label is the identifier followed by the @ symbol. For example, abc@ and fooBar@ are all valid labels. To label an expression, we just need to add a label before it
loop@ for (i in 1..100) {
// ……
}
Now, we can restrict break or continue with labels
loop@ for (i in 1..100) {
for (j in 1..100) {
if (……) break@loop
}
}
The label-limited break jumps to the execution point just after the loop specified by the label. continue continues the next iteration of the loop specified by the label
Return at label
Kotlin has function literals, local functions, and object expressions. So Kotlin functions can be nested. The label-restricted return allows us to return from the outer function. One of the most important uses is to return from lambda expressions. Recall when we wrote this
fun foo() {
ints.forEach {
if (it == 0) return
print(it)
}
}
This return expression returns from the function that most directly surrounds it, namely foo. (Note that this kind of non-local return only supports lambda expressions passed to inline functions.) If we need to return from a lambda expression, we must label it and limit the return
fun foo() {
ints.forEach lit@ {
if (it == 0) return@lit
print(it)
}
}
Now, it will only return from lambda expressions. It is usually more convenient to use implicit tags. The label has the same name as the function that accepts the lambda
fun foo() {
ints.forEach {
if (it == 0) return@forEach
print(it)
}
}
Or, we can substitute an anonymous function for the lambda expression. The return statement inside the anonymous function will return from the anonymous function itself
fun foo() {
ints.forEach(fun(value: Int) {
if (value == 0) return
print(value)
})
}
When a return value is to be returned, the parser prefers to use the label-restricted return, that is
return@a 1
It means "return 1 from label @a", not "return an expression marked by a label (@a 1)"
for (i in 1..4) print(i) // 打印结果为: "1234"
for (i in 4 downTo 1) print(i) // 打印结果为: "4321"
for (i in 1..4 step 2) print(i) // 打印结果为: "13"
for (i in 4 downTo 1 step 2) print(i) // 打印结果为: "42"
for (i in 1 until 10) { // i in [1, 10), 不包含 10
println(i)
}