Kotlin Array reduceIndexed Function

The reduceIndexed function in Kotlin is used to accumulate a value by applying a specified binary operation from left to right to the elements of an array, while also providing the index of each element. This function is part of the Kotlin standard library and allows for more complex reduction operations that require knowledge of the element's index.

Table of Contents

  1. Introduction
  2. reduceIndexed Function Syntax
  3. Understanding reduceIndexed
  4. Examples
    • Basic Usage
    • Using reduceIndexed with Custom Types
    • Handling Edge Cases
  5. Real-World Use Case
  6. Conclusion

Introduction

The reduceIndexed function processes the elements of an array and combines them into a single result by repeatedly applying a given operation, starting with the first element. It also provides the index of each element, allowing for more complex reduction operations that need to take the index into account.

reduceIndexed Function Syntax

The syntax for the reduceIndexed function is as follows:

inline fun <S, T : S> Array<out T>.reduceIndexed(operation: (index: Int, acc: S, T) -> S): S

Parameters:

  • operation: A lambda function that takes the index of the element, the accumulated value, and the current element, and returns the new accumulated value.

Returns:

  • The accumulated value after processing all elements in the array.

Understanding reduceIndexed

The reduceIndexed function starts with the first element of the array as the initial accumulator value and then applies the given operation to each element from left to right, along with its index. The result of each operation becomes the new accumulator value, which is passed to the next iteration.

Examples

Basic Usage

To demonstrate the basic usage of reduceIndexed, we will create an array of integers and calculate their weighted sum using the reduceIndexed function, where each element is multiplied by its index before being added to the sum.

Example

fun main() {
    val numbers = arrayOf(1, 2, 3, 4, 5)
    val weightedSum = numbers.reduceIndexed { index, acc, number -> acc + index * number }
    println("Weighted sum of numbers: $weightedSum")
}

Output:

Weighted sum of numbers: 40

Using reduceIndexed with Custom Types

This example shows how to use reduceIndexed to combine elements in an array of custom objects, taking the index into account.

Example

data class Person(val name: String, val age: Int)

fun main() {
    val people = arrayOf(
        Person("Ravi", 25),
        Person("Anjali", 30),
        Person("Priya", 22)
    )

    val totalAgeWithIndex = people.reduceIndexed { index, acc, person ->
        Person("", acc.age + person.age + index)
    }.age
    println("Total age with index of all people: $totalAgeWithIndex")
}

Output:

Total age with index of all people: 80

Handling Edge Cases

This example demonstrates how to handle an empty array using the reduceIndexed function. Note that reduceIndexed will throw an exception if used on an empty array, so we need to handle this case.

Example

fun main() {
    val numbers = arrayOf<Int>()
    val weightedSum = if (numbers.isNotEmpty()) {
        numbers.reduceIndexed { index, acc, number -> acc + index * number }
    } else {
        0
    }
    println("Weighted sum of numbers: $weightedSum")
}

Output:

Weighted sum of numbers: 0

Real-World Use Case

Aggregating Data with Index Information

In real-world applications, the reduceIndexed function can be used to aggregate data that depends on both the value and the index of the elements, such as calculating a weighted sum or adjusting values based on their position.

Example

data class Transaction(val id: Int, val amount: Double)

fun main() {
    val transactions = arrayOf(
        Transaction(1, 100.0),
        Transaction(2, 150.0),
        Transaction(3, 200.0)
    )

    val totalWeightedRevenue = transactions.reduceIndexed { index, acc, transaction ->
        Transaction(0, acc.amount + (index + 1) * transaction.amount)
    }.amount
    println("Total weighted revenue: $totalWeightedRevenue")
}

Output:

Total weighted revenue: 1000.0

Conclusion

The reduceIndexed function in Kotlin is used for performing reduction operations on arrays that require knowledge of the element's index. It allows you to accumulate a value by applying a specified binary operation to the elements of an array, starting with the first element and taking the index into account. 

By understanding and using this function, you can effectively manage complex aggregation operations in your Kotlin applications.

Comments