📜  Kotlin for Loop(1)

📅  最后修改于: 2023-12-03 15:02:32.131000             🧑  作者: Mango

Kotlin for Loop

In Kotlin, there are multiple ways to use a for loop to iterate over a collection of elements. In this tutorial, we will cover some of these ways along with examples.

Syntax

The basic syntax of a for loop in Kotlin is:

for (item in collection) {
    // code to execute for each item
}

where:

  • item is a variable name that you choose to represent each element in the collection.
  • collection is the name of the collection that you want to loop through.
Looping over Collections
ArrayList

Suppose we have an ArrayList of Integers and we want to iterate through all the elements of the list. We can do that using the for loop as shown below:

val numbers = arrayListOf(1, 2, 3, 4, 5)

for (num in numbers) {
    println(num)
}
Map

Suppose we have a Map containing the names and ages of people, and we want to iterate through all the entries in the map. We can do that using the for loop as shown below:

val ages = mapOf("Alice" to 27, "Bob" to 23, "Charlie" to 30)

for ((name, age) in ages) {
    println("$name is $age years old")
}

A few things to note here:

  • name and age are variable names that we choose to represent the keys and values of the map, respectively.
  • We use destructuring declaration to extract the keys and values of each entry in the map.
Looping with Indices

Sometimes, we may want to iterate through a collection using its indices instead of its elements. We can do that using the indices property of the collection. For example:

val numbers = arrayListOf(1, 2, 3, 4, 5)

for (i in numbers.indices) {
    println("Index $i has value ${numbers[i]}")
}
Looping with Ranges

Kotlin provides an easy way to loop through a range of values using the rangeTo() function. For example:

for (i in 1..10) {
    println(i)
}

This will print out the numbers from 1 to 10 (both inclusive).

Conclusion

In this tutorial, we learned about different ways to use a for loop in Kotlin. We covered looping over collections, looping with indices, and looping with ranges. Hope this was helpful!