Kotlin List withIndex()
Syntax & Examples
Syntax of List.withIndex()
The syntax of List.withIndex() extension function is:
fun <T> Iterable<T>.withIndex(): Iterable<IndexedValue<T>>
This withIndex() extension function of List returns a lazy Iterable that wraps each element of the original collection into an IndexedValue containing the index of that element and the element itself.
✐ Examples
1 Example
In this example,
- We create a list named
list
containing the characters'a', 'p', 'p', 'l', 'e'
. - We use the
withIndex()
extension function onlist
to create an iterable of indexed values. - We iterate over the indexed list using a loop and print each index-value pair to standard output.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf("a", "p", "p", "l", "e")
val indexedList = list.withIndex()
for ((index, value) in indexedList) {
println("Index: \$index, Value: \$value")
}
}
Output
Index: 0, Value: a Index: 1, Value: p Index: 2, Value: p Index: 3, Value: l Index: 4, Value: e
2 Example
In this example,
- We create a list named
list
containing the integers10, 20, 30
. - We use the
withIndex()
extension function onlist
to create an iterable of indexed values. - We iterate over the indexed list using a loop and print each index-value pair to standard output.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf(10, 20, 30)
val indexedList = list.withIndex()
for ((index, value) in indexedList) {
println("Index: \$index, Value: \$value")
}
}
Output
Index: 0, Value: 10 Index: 1, Value: 20 Index: 2, Value: 30
3 Example
In this example,
- We create a list named
list
containing the strings'apple', 'banana', 'cherry'
. - We use the
withIndex()
extension function onlist
to create an iterable of indexed values. - We iterate over the indexed list using a loop and print each index-value pair to standard output.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf("apple", "banana", "cherry")
val indexedList = list.withIndex()
for ((index, value) in indexedList) {
println("Index: \$index, Value: \$value")
}
}
Output
Index: 0, Value: apple Index: 1, Value: banana Index: 2, Value: cherry
Summary
In this Kotlin tutorial, we learned about withIndex() extension function of List: the syntax and few working examples with output and detailed explanation for each example.