Eyes, JAPAN Blog > Kotlin For loop

Kotlin For loop

Tang

Basic usage

1. Until keyword

“`kotlin
for (i in 0 until 100) {
println(i) // Output: 0 ~ 99
}
“`
The final output result includes 0 but not 100
“`
0
1
2
98
99
“`

2. Use .. to include the end value

`..` is called the range operator in Kotlin, it represents a closed range, and both sides need a number when using it
“`kotlin
for (i in 0..100) {
println(i) // Output: 0 ~ 100
}
“`
The final output result includes 0 and 100
“`
0
1
2
98
99
100
“`
* Note: `..` also support calim a variable as a range, and the variable represents a range. When looping, the variable will loop through the range
“`kotlin
val test = 0..100
“`
But `..` can only create an ascending range, that is, from small to large, not from large to small. If you want to loop from large to small, you need to use another keyword `downTo`

3. Use downTo to loop from large to small

`downTo` is a keyword in Kotlin, which is used to loop from large to small. It is used in conjunction with the range operator `..`
“`kotlin
for (i in 100 downTo 0) {
println(i) // Output: 100 ~ 0
}
“`
You will suddenly realize why it is 100 ~ 0 instead of 100 ~ 1. In fact, it was mentioned at the end of the introduction of the keyword. In terms of descending loop, the `downTo` keyword generates a left-closed and right-closed interval.

4. Step keyword

The default step size in Kotlin is 1 when looping. If you want to change the step size, you can use the `step` keyword
“`kotlin
for (i in 0..100 step 2) {
println(i) // Output: 0, 2, 4, 6, 8, …, 100
}
“`

Recurring Arrays or Lists

The above expressions are all about how to loop from one number to another. In fact, in many cases, the loop is to get the values in a container such as ArrayList. In Kotlin, the operations of looping these containers are very simple

1. Loop through an array or list

“`kotlin
val arrayList = arrayListOf(1, 2, 3, 4, 5, 6, 12, 31, 23, 123, 12, 3, 123, 2)
“`
* Directly use the `in` keyword to loop through the array or list
“`kotlin
for (i in arrayList) {
println(i) // Output: 1, 2, 3, 4, 5, 6, 12, 31, 23, 123, 12, 3, 123, 2
}
“`

* Get the index and value of the array or list

It is very simple to get the index and value of the array or list in Kotlin. You only need to use the `withIndex()` method of the container
“`kotlin
for ((index, value) in arrayList.withIndex()) {
println(“Index: $index, Value: $value”)
// Output: Index: 0, Value: 1, Index: 1, Value: 2, Index: 2, Value: 3, …
}
“`

* Iterate through an array or list by index

“`kotlin
for (i in 0 until arrayList.size) {
println(arrayList[i]) // 输出: 1,2,3,4….2
}
“`
There will be a yellow line under this code. In fact, the above method is not recommended. Because the `size` method of the container is called every time, it is not efficient. It is recommended to use the `indices` property of the container
“`kotlin
for (i in arrayList.indices) {
println(arrayList[i]) // Output: 1,2,3,4….2
}
“`
** Iterable interface
In Kotlin, the for loop can iterate over a wide range of data containers beyond just arrays and lists, as long as the container implements the Iterable interface. This includes sets, maps, and custom collections. The ability to iterate over different types of containers using the for loop makes Kotlin highly versatile for handling various data structures in everyday development. For more detailed exploration, developers are encouraged to experiment with different iterable containers in their projects.
Iterating over a set
“`kotlin
val set = setOf(1.0, 2.0, 3.0)
for (element in set) {
println(element) // Output: 1.0, 2.0, 3.0
}
“`
Iterating over a map
“`kotlin
val map = mapOf(“a” to 1, “b” to 2, “c” to 3)
for ((key, value) in map) {
println(“$key -> $value”) // Output: a -> 1, b -> 2, c -> 3
}
“`
Iterating over a custom collection
“`kotlin
class MyIterable : Iterable<Int> {
private val data = listOf(1, 2, 3)
override fun iterator(): Iterator<Int> {
return data.iterator()
}
}
val myIterable = MyIterable()
for (element in myIterable) {
println(element)
}
“`

Multiple variables in for loop

The multi-variable for loop in java translates directly into while syntax in Kotlin, but while causes the number of lines of code to skyrocket, is not very readable, and creates local variables.
“`Java
// Before translation
for (int i = 0, j = 100; i < 100 && j > 0; i++, j–) {
System.out.println(“i: ” + i + “, j: ” + j); // Output: i: 0, j: 100 ~ i: 99, j: 1
}
“`
“`kotlin
// After translation
var i = 0
var j = 100
while (i < 100 && j > 0) {
println(“i: $i, j: $j”) // Output: i: 0, j: 100 ~ i: 99, j: 1
i++
j–
}
“`
The above code is not recommended, because it is not efficient and not readable. In fact, Kotlin also supports multi-variable for loop, but the syntax is slightly different from Java
“`kotlin
for ((i, j) in (0 until 100).zip(100 downTo 0)) {
println(“i: $i, j: $j”) // Output: i: 0, j: 100 ~ i: 99, j: 1
}
“`

* Default values for multiple variables

In Kotlin’s for, the in keyword is usually used in front of the in keyword to define the variables of the loop, or used to indicate the index or each element of the looped container, but here we don’t consider the looped container, we only consider the variables of the loop. When you need to define more than one variable, you define them inside (), and each variable is separated by a comma. after the in keyword, you set the loop interval.
“`kotlin
for((i,j) in…){
}
“`

* Set the loop interval

In fact, when defining a loop variable in kotlin’s for loop, it doesn’t give it an initial value, but directly specifies the interval it needs to loop over and whether it’s a descending or an orthogonal loop, so the in loop described above is preceded by a defined variable rather than an initial value.
Now set the loop intervals for the loop variables defined above. Multiple loop intervals are set using the `.zip()` function.
“`kotlin
for ((i, j) in (0 until 100).zip(100 downTo 0)) {
}
// output: i: 0, j: 100 ~ i: 99, j: 1
“`
The above code means that the i variable loops from 0 to 99, and the j variable loops from 100 to 1. The two variables are looped in parallel, and the loop ends when the smaller loop ends.
* Triple/Qudruple variables in for loop
Sometimes the loop variables are three or four, and you will find it difficult to start again. Try using zip().zip() and you will find that it gives you an error
“`kotlin
for((i,j,k) in (0..100).zip(0..100).zip(0..100)){} // Error code
“`
Error message:
> Kotlin: Destructuring declaration initializer of type Pair<Pair<Int, Int>, Int> must have a ‘component3()’ function
The error message tells us that the Pair class does not have a component3() function, so we need to use the `Pair` class to wrap the `Pair` class, and then use the `component1()`, `component2()`, and `component3()` functions to get the values
“`kotlin
for ((i, jPair) in (1..100).zip((0..100).zip(0..100)) ) {
println(“i: $i, $jPair”)
}
// Output: i: 1, Pair(0, 0); i: 2, Pair(1, 1); i: 3, Pair(2, 2); … i: 100, Pair(99, 99)
“`
What if you want to get the values of the inner Pair class?
“`kotlin
for ((i, jPair) in (1..100).zip((0..100).zip(0..100))) {
println(“i: $i | jPair.firstValue: ${jPair.first} | jPair.secondValue: ${jPair.second}”)
}
/* Output: i: 1 | jPair.firstValue: 0 | jPair.secondValue: 0;
i: 2 | jPair.firstValue: 1 | jPair.secondValue: 1;
i: 3 | jPair.firstValue: 2 | jPair.secondValue: 2;
i: 100 | jPair.firstValue: 99 | jPair.secondValue: 99
*/
“`
So quratuple variables can be achieved like this
“`kotlin
for ((iPair, jPair) in ((1..100).zip(1..100)).zip((0..100).zip(0..100))) {
println(“iPair: $iPair | jPair: $jPair”)
}
“`

Jump expression

Kotlin provides a jump expression to jump out of a loop. The jump expression includes break, continue, and return. The break expression is used to jump out of the loop, and the continue expression is used to skip the current loop and continue to the next loop. The return expression is used to jump out of the loop and return a value. The jump expression can be used in a loop or a when expression.

Label

In Kotlin, you can use a label to specify which loop to jump out of. The label is followed by an @ symbol and a name. The label is placed before the loop, and the jump expression is followed by the label name. The label is used to specify which loop to jump out of when there are multiple nested loops.
“`kotlin
all@ for (i in 0 until 100) {
inner@ for (j in 100 downTo 0) {
if (i == 60) break@inner
if (j == 60) continue@all
println(“j: $j”)
}
println(“i: $i”)
}
“`
The above code uses the label to specify which loop to jump out of. The inner loop is labeled inner, and the outer loop is labeled all. When i is equal to 60, the inner loop is jumped out of, and when j is equal to 60, the outer loop is jumped out of.

Comments are closed.