Kotlin Array - runningReduce() Function



The Kotlin array runningReduce() function is used to return a list of successive accumulated values. It iterates through each element in the array from left to right, applying an operation to the current element and the accumulated result of its predecessors.

That acc value passed to operation function should not be mutated; otherwise it would affect the previous value in resulting list

Syntax

Following is the syntax of Kotlin array runningReduce() function −

fun <S, T : S> Array<out T>.runningReduce(
    operation: (acc: S, T) -> S
): List<S>

Parameters

This function accepts a parameters operation − Function that takes current accumulator value and the element, and calculates the next accumulator value.

Return value

The function returns a list containing successive accumulation values.

Example 1

The following is a basic example to demonstrate the use of runningReduce() function −

fun main(args: Array<String>) {
   val numbers = arrayOf(1, 2, 3, 4, 5)
   val res = numbers.runningReduce({acc, num->acc + num})
   println("list: $res")
}

Output

The above code generate following output −

list: [1, 3, 6, 10, 15]

Example 2

Now, Let's see another example. Here, we use the runningReduce function to accumulate each string to the previously accumulated string −

fun main(args: Array<String>) {
   val characters = arrayOf<String>("a", "b", "c", "d", "e")
   val res = characters.runningReduce({acc, char->acc + char})
   println("list: $res")
}

Output

Following is the output −

list: [a, ab, abc, abcd, abcde]

Example 3

The below example explain the runningReduce() function will work or not if an array is empty −

fun main(args: Array<String>) {
   val numbers = arrayOf<Int>()
   val list = numbers.runningReduce { acc, num -> acc + num}
   println("list: $list")
}

Output

The above code produced an empty list if an array is empty −

list: []
kotlin_arrays.htm
Advertisements