How to Use Indices in Kotlin: Syntax and Examples
In Kotlin, you can use
indices to get the valid index range of a collection like a list or array. Use collection.indices to loop through or access elements safely by their index.Syntax
The indices property returns an IntRange representing all valid indices of a collection. You can use it in loops or to check index bounds.
collection.indices: Gets the range of valid indices.for (i in collection.indices): Loop through all indices.collection[i]: Access element at indexi.
kotlin
val list = listOf("a", "b", "c") for (i in list.indices) { println("Index: $i, Value: ${list[i]}") }
Output
Index: 0, Value: a
Index: 1, Value: b
Index: 2, Value: c
Example
This example shows how to use indices to loop through a list and print each index with its value.
kotlin
fun main() {
val fruits = listOf("Apple", "Banana", "Cherry")
for (index in fruits.indices) {
println("Fruit at index $index is ${fruits[index]}")
}
}Output
Fruit at index 0 is Apple
Fruit at index 1 is Banana
Fruit at index 2 is Cherry
Common Pitfalls
One common mistake is to assume indices start at 1 or to access an index outside the valid range, which causes an IndexOutOfBoundsException. Always use indices to safely loop through valid indexes.
Wrong way (may cause error):
for (i in 1..list.size) {
println(list[i]) // Error: index out of bounds at last iteration
}Right way:
for (i in list.indices) {
println(list[i])
}Quick Reference
collection.indices: Gets valid index range (0 until size).- Use in
forloops to access elements by index. - Prevents out-of-bound errors by limiting index range.
Key Takeaways
Use
collection.indices to get the valid index range of a collection.Loop with
for (i in collection.indices) to safely access elements by index.Avoid accessing indices outside
indices to prevent errors.Indices always start at 0 and go up to
size - 1.Using
indices makes your code safer and clearer.