Kotlin Loop Control
For Loop
A for loop can iterate over any object that provides an iterator, with the syntax 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 iterate over any object that provides an iterator.
If you want to iterate over an array or a list by index, you can do so like this:
for (i in array.indices) {
print(array[i])
}
Note that this "iteration over a range" compiles into an optimized implementation without creating additional objects.
Alternatively, you can use the library function withIndex:
for ((index, value) in array.withIndex()) {
println("the element at $index is $value")
}
Example
Iterating over a 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:
apple
banana
kiwi
item at 0 is apple
item at 1 is banana
item at 2 is kiwi
while and do...while Loops
while is the most basic loop, with the structure as follows:
while (boolean expression) {
// loop content
}
do…while loop Unlike the while statement, sometimes we need to execute at least once even if the condition is not met.
The do…while loop is similar to the while loop, but the difference is that the do…while loop will execute at least once.
do {
// code statement
}while (boolean expression);
Example
fun main(args: Array<String>) {
println("----while usage-----")
var x = 5
while (x > 0) {
println(x--)
}
println("----do...while usage-----")
var y = 5
do {
println(y--)
} while (y > 0)
}
Output:
5
4
3
2
1
----do...while usage-----
5
4
3
2
1
Return and Jump
Kotlin has three structured jump expressions:
return. By default, it returns from the most directly enclosing function or anonymous function.
break. Terminates the most directly enclosing loop.
continue. Continues to the next iteration of the most directly enclosing loop.
In loops, Kotlin supports traditional break and continue operators.
fun main(args: Array<String>) {
for (i in 1..10) {
if (i == 3) continue // Skip the current loop and continue to the next loop when i is 3
println(i)
if (i > 5) break // Break out of the loop when i is 6
}
}
Output:
1
2
4
5
6
Break and Continue Labels
In Kotlin, any expression can be labeled with a label. The format of the label is an identifier followed by an @ symbol, for example: abc@, fooBar@ are all valid labels. To label an expression, simply add the label in front of it.
loop@ for (i in 1..100) {
// ...
}
Now, we can limit break or continue with labels:
loop@ for (i in 1..100) {
for (j in 1..100) {
if (...) break@loop
}
}
A label-limited break jumps to the execution point immediately following the loop specified by the label. Continue continues to the next iteration of the loop specified by the label.
Return at Label
Kotlin has function literals, local functions, and object expressions. Therefore, Kotlin functions can be nested. Label-limited return allows us to return from the outer function. One of the most important uses is to return from a lambda expression. Recall when we wrote like this:
fun foo() {
ints.forEach {
if (it == 0) return
print(it)
}
}
This return expression returns from the most directly enclosing function, i.e., foo. (Note, this 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 with it.
``` fun foo() { ints.forEach lit@ { if