[Doc Review]reduce

kotlin-stdlib / kotlin.collections / reduce

Summary

Accumulates value starting with the first element and applying [operation](kotlinlang.org/api/latest/jvm/stdlib/kotlin..) from left to right to current accumulator value and each element.

Parameters

operation - function that takes current accumulator value and an element, and calculates the next accumulator value.

inline fun <S, T : S> Iterable<T>.reduce(
    operation: (acc: S, T) -> S
): S

Tip

  1. Use reduceOrNull() to handle null input.

  2. Can be employed to obtain the sum of an integer list or concatenate the string of a char list.

  3. No need for assignment; leverage the syntax where the last line of the lambda is automatically returned to accumulate values.

In Practice

Even sum

class Solution {
    fun solution(n: Int): Int {
        // return (1..n).filter{it % 2 == 0}.sum()
        return (0..n).reduce{ acc, num ->
            if(num%2==0){
                acc+num
            }else{
                acc
            }
        }
    }
}

Example

val strings = listOf("a", "b", "c", "d")
println(strings.reduce { acc, string -> acc + string }) // abcd
println(strings.reduceIndexed { index, acc, string -> acc + string + index }) // ab1c2d3

// emptyList<Int>().reduce { _, _ -> 0 } //  will fail

Supported Data Types

  • Array

  • ByteArray

  • ShortArray

  • IntArray

  • LongArray

  • FloatArray

  • DoubleArray

  • CharArray

References

https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/average.html