DEV Community

λeo
λeo

Posted on • Updated on

Kotlin Collections - withIndex

To retrieve elements with an index from an iterable type use withIndex function.
The method iterates over an iterable type and creates another iterable type with indexed values.
It is going to take O(n) time and O(n) space.

Documentation:
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/with-index.html
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-indexed-value/


val listOfFruits : List<String> = listOf("pineapple", "apple", "orange") 
// ["pineapple", "apple", "orange"]

val fruitsWithIndex : Iterable<IndexedValue<String>> = listOfFruits.withIndex() 
//[IndexedValue(0,"pineapple"),IndexedValue(1,"apple"),IndexedValue(0,"orange"]

val firstFruit = fruitsWithIndex.elementAt(0)
println("Index: ${firstFruit.index}, Value: ${firstFruit.value}") 
//Index: 0, Value: pineapple

Top comments (0)