Skip to content
DeveloperMemos

Different Ways to Loop Through an Array in Kotlin

Kotlin, Arrays1 min read

Arrays are a fundamental data structure in programming and Kotlin provides several ways to iterate over them. In this article, we will discuss each of these methods in detail.

Using a for loop

The most common way to loop through an array is by using a for loop. Here's an example:

1val numbers = arrayOf(1, 2, 3, 4, 5)
2
3for (number in numbers) {
4 // do something with number
5}

In this example, we declare an array of integers called numbers. We then use a for loop to iterate through the array and perform some action on each element.

Using forEach()

Another way to loop through an array in Kotlin is by using the forEach() method. This method takes a lambda expression as its argument, which is executed for each element in the array. Here's an example:

1val numbers = arrayOf(1, 2, 3, 4, 5)
2
3numbers.forEach { number ->
4 // do something with number
5}

In this example, we call the forEach() method on the numbers array and pass in a lambda expression that performs some action on each element.

Using indices

Sometimes, you may need to access both the index and the value of each element in an array. In such cases, you can use the indices property of the array to iterate through the array's indices, like so:

1val numbers = arrayOf(1, 2, 3, 4, 5)
2
3for (index in numbers.indices) {
4 val number = numbers[index]
5 // do something with index and number
6}

In this example, we use a for loop to iterate through the indices of the numbers array. We then use each index to access the corresponding element in the array.

Using withIndex()

Another way to access both the index and value of each element in an array is by using the withIndex() function. This function returns a Iterable of IndexedValue objects, where each object contains the index and value of an element in the array. Here's an example:

1val numbers = arrayOf(1, 2, 3, 4, 5)
2
3for ((index, number) in numbers.withIndex()) {
4 // do something with index and number
5}

In this example, we use a for loop to iterate through the IndexedValue objects returned by the withIndex() function. We then extract the index and value of each element from the IndexedValue object.