loading...

Kotlin Collections - withIndex

0xleonerd profile image λeo Updated on ・1 min read

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

Discussion

markdown guide