While iterate list or array of the data we may require to handle the data with index of the current item. How do we get index while iterate the list/array data with forEach loop.
In kotlin we have different ways to iterate the list/array data
forEachIndexed loop is an inline function which will takes inout as an array and reads index and values step by step.
fun main() { var topics = listOf("Kotlin", "Kotlin array", "Kotlin List", "Kotlin Functions") topics.forEachIndexed {index, element -> println("index = $index, item = $element ") } } |
Output:
index = 0, item = Kotlin |
fun main() { var topics = listOf("Kotlin", "Kotlin array", "Kotlin List", "Kotlin Functions") for ((index, value) in topics.withIndex()) { println("The topics of $index is $value") } } |
Output:
The topics of 0 is Kotlin |
Article Contributed By :
|
|
|
|
76 Views |