How to get the current index of an array while using forEach loop in Kotlin?


Sometimes it becomes necessary to access the index of an array. In this article, we will see how we can access the index of an array in Kotlin while using forEach loop.

Example: Using forEachIndexed()

nstead of using forEach() loop, you can use the forEachIndexed() loop in Kotlin. forEachIndexed is an inline function which takes an array as an input and its index and values are separately accessible.

In the following example, we will traverse through the "Subject" array and we will print the index along with the value.

Example

fun main() {
   var subject = listOf("Java", "Kotlin", "JS", "C")

   subject.forEachIndexed {index, element ->
      println("index = $index, item = $element ")
   }
}

Output

It will generate the following output −

index = 0, item = Java
index = 1, item = Kotlin
index = 2, item = JS
index = 3, item = C

Example: Using withIndex()

withIndex() is a library function of Kotlin using which you can access both the index and the corresponding values of an array. In the following example, we will be using the same array and we will be using withIndex() to print its values and index. This has to be used with a for loop.

Example

fun main() {
   var subject=listOf("Java", "Kotlin", "JS", "C")

   for ((index, value) in subject.withIndex()) {
      println("The subject of $index is $value")
   }
}

Output

It will generate the following output −

The subject of 0 is Java
The subject of 1 is Kotlin
The subject of 2 is JS
The subject of 3 is C

Updated on: 27-Oct-2021

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements