Get the Current Index of for each Loop in Kotlin

Kotlin provides a variety of tools for working with for each loops, enabling developers to easily iterate through collections and other data structures. One useful feature is the ability to get the current index of a loop iteration. This allows you to keep track of your position within a list or array, making it easier to process each item individually or perform complex calculations based on the current position.

There are several different functions that can be used for this purpose. Each of these functions handles slightly different cases, so it’s important to use the appropriate one in your code.

list.forEachIndexed { index, element ->
    Log.e("$index", element.toString())
for (i in list.indices) {
    Log.e("VALUE", list[i].toString())
for ((index, element) in list.withIndex()) {
     Log.e("$index", element.toString())
listOf("Samsung", "Huawei", "Apple", "Oppo")
    .filterIndexed { index, _ ->  index % 2 != 0 }
    .forEach { Log.e("VALUE", it) }

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.