Kotlin List fold()
Syntax & Examples


Syntax of List.fold()

The syntax of List.fold() extension function is:

fun <T, R> Iterable<T>.fold( initial: R, operation: (acc: R, T) -> R ): R

This fold() extension function of List accumulates value starting with initial value and applying operation from left to right to current accumulator value and each element.



✐ Examples

1 Example

In this example,

  • We create a list named list containing strings representing fruits.
  • We apply the fold function on list starting with the initial value "Fruits:".
  • The operation concatenates each fruit with the accumulator string acc.
  • The resulting string is printed to standard output.

Kotlin Program

fun main(args: Array<String>) {
    val list = listOf("apple", "banana", "cherry");
    val result = list.fold("Fruits:") { acc, fruit -> "$acc $fruit" };
    println(result);
}

Output

Fruits: apple banana cherry

2 Example

In this example,

  • We create a list named list containing integers.
  • We apply the fold function on list starting with the initial value 0.
  • The operation accumulates the sum of all numbers.
  • The resulting sum is printed to standard output.

Kotlin Program

fun main(args: Array<String>) {
    val list = listOf(10, 20, 30);
    val result = list.fold(0) { acc, number -> acc + number };
    println(result);
}

Output

60

3 Example

In this example,

  • We create a list named list containing characters representing alphabets.
  • We apply the fold function on list starting with the initial value "Alphabets:".
  • The operation concatenates each character with the accumulator string acc.
  • The resulting string is printed to standard output.

Kotlin Program

fun main(args: Array<String>) {
    val list = listOf('a', 'b', 'c');
    val result = list.fold("Alphabets:") { acc, char -> "$acc $char" };
    println(result);
}

Output

Alphabets: a b c

Summary

In this Kotlin tutorial, we learned about fold() extension function of List: the syntax and few working examples with output and detailed explanation for each example.