Avatar ·

How to get the current element index in a forEach loop in Kotlin?

Hello, colleagues! I've just started learning Kotlin and encountered a problem when working with loops. In Java, I'm used to using a regular for loop with an index, for example: ```java for (int i = 0; i < list.size(); i++) { System.out.println(i + ": " + list.get(i)); } ``` But in Kotlin, I see that everyone recommends using forEach: ```kotlin list.forEach { item -> println(item) } ``` This is convenient, but what if I need not only the element itself but also its index? For example, I want to output a list of tasks with numbers: ```kotlin val tasks = listOf("Buy bread", "Wash dishes", "Do homework") tasks.forEach { task -> println("$index: $task") // Error! index is not defined } ``` Here I get a compilation error because the index variable doesn't exist. I tried to create a separate