Kotlin List.reduce() – Examples

Kotlin List reduce()

The List reduce() function in Kotlin is used to apply an operation sequentially to all elements in a list and accumulate the result. It starts with an initial value and combines elements from left to right using the specified operation.

Syntax

The reduce() function takes two parameters:

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

where:

ParameterDescription
operationA function that takes an accumulator of type S and an element of type T, and returns a new accumulator of type S.

Return Value

The reduce() function returns the final accumulated value after applying the operation to all elements in the list.

Example 1: Summing Numbers

This example demonstrates how to use reduce() to calculate the sum of numbers in a list.

In this example,

  1. Create a list of numbers, numbers.
  2. Use reduce() to sum all numbers in the list.
  3. The reduce() function adds each number to the accumulator, starting with an initial value of 0.

Kotlin Program

fun main() {
    val numbers = listOf(1, 2, 3, 4, 5)
    val sum = numbers.reduce { acc, num -> acc + num }
    println("Sum of numbers: $sum")
}

Output

Kotlin List reduce() - Example 1 for summing numbers

Example 2: Concatenating Strings

In this example, we use reduce() to concatenate strings in a list.

In this example,

  1. Create a list of strings, words.
  2. Use reduce() to concatenate all strings in the list.
  3. The reduce() function concatenates each string to the accumulator, starting with an initial value of an empty string.

Kotlin Program

fun main() {
    val words = listOf("Hello", ", ", "world", "!")
    val sentence = words.reduce { acc, word -> acc + word }
    println("Concatenated sentence: $sentence")
}

Output

Kotlin List reduce() - Example 2 for concatenating strings

Summary

The reduce() function in Kotlin is useful for performing operations that involve accumulating values, such as summing numbers or concatenating strings. It applies the specified operation sequentially to all elements in the list and accumulates based on the accumulation expression.