Kotlin Training Program

DOWNLOAD APP

FEEDBACK

Reduce

To accumulate a single value from of a list of items, we use the reduce() function. Following example demonstrates the use of reduce() function to find out the longest word from a list of words :

 fun main() {
    val words = listOf("apple", "banana", "cherry", "date")
    val longestWord = words.reduce { acc, word ->
        if (word.length > acc.length) word else acc
    }
    println(longestWord) // Prints "banana"
}
 

reduce() function takes a lambda accumulator: (T, T) → T where first input argument is the value accumulated so far and second input argument is the current value. Output of lambda is the new accumulates value. This lambda is invoked for each item in the list one after another.

Similarly we have fold() function, the only difference is that fold() takes an initial value while reduce() doesn’t.

Lets implement a common function for both reduce & fold operations. It will take two parameters :

To accumulate the value, we iterate over the collection and update the acc by invoking the accumulator lambda with latest value of acc & the current element.

 fun <T> List<T>.reduce(
        initialValue: T = firstOrNull() ?: error("Empty collection can't be reduced!"),
        accumulator: (T, T) -> T
): T {
    var acc = initialValue
    for (i in 1..lastIndex) {
        acc = accumulator(acc, get(i))
    }
    return acc
}