Sling Academy
Home/Kotlin/Kotlin: Iterating Through Arrays with Loops and `forEach`

Kotlin: Iterating Through Arrays with Loops and `forEach`

Last updated: December 04, 2024

Kotlin is a modern programming language that provides several ways to iterate through arrays. Whether you're working with mutable arrays or immutable lists, understanding these mechanisms can enhance both the readability and performance of your code. In this article, we'll explore how to iterate through arrays using loops and the forEach lambda in Kotlin, with practical examples to guide you through each approach.

Using the Traditional for Loop

The traditional for loop in Kotlin resembles those in many other languages, offering you an index-based way to iterate over an array. Let's start with a simple example:

fun main() {
    val fruits = arrayOf("Apple", "Banana", "Cherry")
    for (i in fruits.indices) {
        println("Element at index $i is ${fruits[i]}")
    }
}

In this example, we use fruits.indices, which provides the range of valid indices for the array, making it easy to access each element along with its index.

The for-each Style Loop

Kotlin simplifies iteration over collections with a for-each style loop, which can directly iterate over elements:

fun main() {
    val cars = arrayOf("Ford", "Toyota", "Tesla")
    for (car in cars) {
        println("Car brand: $car")
    }
}

Here, iteration happens over the elements directly, so you don't explicitly handle indices. This approach leads to cleaner code and is less error-prone when you don't need the index.

Iterating with the forEach Function

The forEach method in Kotlin is a higher-order function that allows you to perform actions on each element of a collection using lambda expressions. Here's an example:

fun main() {
    val colors = arrayOf("Red", "Green", "Blue")
    colors.forEach { color ->
        println("Color: $color")
    }
}

In this case, the lambda expression takes each element of the colors array and executes the print statement. The variable color inside the lambda holds the current element being processed.

Using withIndex for Index and Value

If you need both the index and the value during iteration, Kotlin provides a convenient way using the withIndex extension function:

fun main() {
    val animals = arrayOf("Dog", "Cat", "Rabbit")
    for ((index, animal) in animals.withIndex()) {
        println("Animal at index $index is $animal")
    }
}

The withIndex function returns an IndexedValue object which you can destructure to get both the index and value seamlessly.

Using Range Until Array Size

Alternatively, you can cycle through an array by manually specifying a range. Below is how you can implement it:

fun main() {
    val numbers = arrayOf(1, 2, 3, 4, 5)
    for (i in 0 until numbers.size) {
        println("Number at index $i is ${numbers[i]}")
    }
}

The until function creates an exclusive range that doesn't include the end value. You start from zero up to numbers.size, ensuring all elements are covered.

Conclusion

Kotlin offers various methods for array iteration, each with its own use-case advantages. While traditional for loops provide fine-grained control over iteration indices, the forEach function enables more expressive and concise code. Mastery of these techniques is crucial for writing idiomatic and efficient Kotlin code. Experiment with the examples above, and choose the iteration method that best suits your task at hand, ensuring clarity and functionality in your code.

Next Article: Kotlin: Finding the Index of an Element in an Array

Previous Article: Kotlin: Accessing and Updating Elements in an Array

Series: Kotlin Collections

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