Sling Academy
Home/Kotlin/Working with Indices in `for` Loops in Kotlin

Working with Indices in `for` Loops in Kotlin

Last updated: December 05, 2024

When working with collections in programming, navigating through each element is a common task. Kotlin, a modern statically typed programming language, provides a concise and expressive syntax for achieving this, which it inherits from its parent language, Java. Today, we'll be discussing how to work with indices within for loops in Kotlin.

Understanding Kotlin's for Loop

Kotlin enhances the traditional loop mechanism by providing features such as range iterations, collections iterations, and enhanced access to indices. In Kotlin, loops can be run without an explicit index counter, reducing the chance of errors inherent in direct index management.

Basic for Loop

To iterate over a collection of items without indices, you can use the simple for loop structure:


val items = listOf("apple", "banana", "cherry")
for (item in items) {
    println(item)
}

This will output:


apple
banana
cherry

But how do you approach a situation where the index is necessary while iterating?

Using Indices with for Loops

Kotlin provides a convenient function called indices that can be used to access the index of items in a collection.

Using indices

You can utilize the indices property to get the range of valid indices for an array or list:


val fruits = listOf("apple", "banana", "cherry")
for (i in fruits.indices) {
    println("Index: $i, Fruit: ${fruits[i]}")
}

This code will output:


Index: 0, Fruit: apple
Index: 1, Fruit: banana
Index: 2, Fruit: cherry

Using withIndex()

An even more Kotlin-idiomatic way to access elements along with their indices is to use the withIndex() function. This utility returns an iterable of IndexedValue instances, each containing the corresponding index and value from the collection:


for ((index, fruit) in fruits.withIndex()) {
    println("Index: $index, Fruit: $fruit")
}

Finally, this loop outputs the same result as previously:


Index: 0, Fruit: apple
Index: 1, Fruit: banana
Index: 2, Fruit: cherry

Practical Applications

These methods are not just useful for simple data displays but can also be crucial when you want to identify an element's position to update, delete, or process elements conditionally based on their index.

For instance, to update elements at even indices, you could write:


val numbers = mutableListOf(1, 2, 3, 4, 5)
for (i in numbers.indices) {
    if (i % 2 == 0) {
        numbers[i] *= 2
    }
}

println(numbers) // Result: [2, 2, 6, 4, 10]

Conclusion

Working with indices in for loops in Kotlin is simple yet powerful, thanks to its intuitive and expressive syntax. Whether you utilize indices or withIndex(), you gain clear and efficient access to both elements and their positions within a collection, mitigating the need for error-prone manual index calculation.

By understanding these concepts, developers can produce reliable and readable code, capitalizing on Kotlin's full potential to simplify and streamline array or list traversal processes.

Next Article: How to Write a `while` Loop in Kotlin

Previous Article: Iterating Through Maps with `for` Loops in Kotlin

Series: Control Flow in Kotlin

Kotlin

You May Also Like

  • How to Use Modulo for Cyclic Arithmetic in Kotlin
  • Kotlin: Infinite Loop Detected in Code
  • Fixing Kotlin Error: Index Out of Bounds in List Access
  • Setting Up JDBC in a Kotlin Application
  • Creating a File Explorer App with Kotlin
  • How to Work with APIs in Kotlin
  • What is the `when` Expression in Kotlin?
  • Writing a Script to Rename Multiple Files Programmatically in Kotlin
  • Using Safe Calls (`?.`) to Avoid NullPointerExceptions in Kotlin
  • Chaining Safe Calls for Complex Operations in Kotlin
  • Using the Elvis Operator for Default Values in Kotlin
  • Combining Safe Calls and the Elvis Operator in Kotlin
  • When to Avoid the Null Assertion Operator (`!!`) in Kotlin
  • How to Check for Null Values with `if` Statements in Kotlin
  • Using `let` with Nullable Variables for Scoped Operations in Kotlin
  • Kotlin: How to Handle Nulls in Function Parameters
  • Returning Nullable Values from Functions in Kotlin
  • Safely Accessing Properties of Nullable Objects in Kotlin
  • How to Use `is` for Nullable Type Checking in Kotlin