Kotlin Sequence fold Function

The fold function in Kotlin is used to accumulate a value starting with an initial value and applying an operation from left to right to the current accumulator value and each element. It is part of the Kotlin standard library and allows you to combine elements of a sequence into a single value by applying a binary operation.

Table of Contents

  1. Introduction
  2. fold Function Syntax
  3. Understanding fold
  4. Examples
    • Basic Usage
    • Folding a Sequence of Strings
    • Using fold with Custom Objects
    • Chaining fold with Other Functions
  5. Real-World Use Case
  6. Conclusion

Introduction

The fold function allows you to combine elements of a sequence into a single value by repeatedly applying a binary operation, starting with an initial value. This is useful for scenarios where you need to aggregate or summarize data, such as computing the sum or product of elements, or even building complex structures like maps.

fold Function Syntax

The syntax for the fold function is as follows:

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

Parameters:

  • initial: The initial value for the accumulator.
  • operation: A lambda function that takes the current accumulator value and the next element, and returns the updated accumulator value.

Returns:

  • The result of accumulating all elements of the sequence, starting with the initial value.

Understanding fold

The fold function works by initializing the accumulator with the specified initial value and then applying the operation to the accumulator and each subsequent element in turn. The final value of the accumulator is returned as the result.

Examples

Basic Usage

To demonstrate the basic usage of fold, we will create a sequence of integers and compute their sum starting with an initial value of 10.

Example

fun main() {
    val numbers = sequenceOf(1, 2, 3, 4, 5)
    val sum = numbers.fold(10) { acc, num -> acc + num }
    println(sum) // Output: 25
}

Output:

25

Folding a Sequence of Strings

This example shows how to fold a sequence of strings by concatenating them, starting with an initial string.

Example

fun main() {
    val words = sequenceOf("Kotlin", "is", "fun")
    val sentence = words.fold("Learning:") { acc, word -> "$acc $word" }
    println(sentence) // Output: Learning: Kotlin is fun
}

Output:

Learning: Kotlin is fun

Using fold with Custom Objects

You can use the fold function to aggregate properties of custom objects.

Example

data class Product(val name: String, val price: Double)

fun main() {
    val products = sequenceOf(
        Product("Laptop", 999.99),
        Product("Smartphone", 499.99),
        Product("Tablet", 299.99)
    )
    val totalPrice = products.fold(0.0) { acc, product -> acc + product.price }
    println(totalPrice) // Output: 1799.97
}

Output:

1799.97

Chaining fold with Other Functions

The fold function can be chained with other sequence functions to perform more complex operations before folding the elements.

Example

fun main() {
    val numbers = sequenceOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
    val result = numbers.filter { it % 2 == 0 }
                        .map { it * 2 }
                        .fold(0) { acc, num -> acc + num }
    println(result) // Output: 60
}

Output:

60

Real-World Use Case

Building a Map from a Sequence

In real-world applications, the fold function can be used to build complex structures, such as maps, from a sequence of elements.

Example

data class Person(val name: String, val age: Int)

fun main() {
    val people = sequenceOf(
        Person("Arjun", 25),
        Person("Bhaskar", 30),
        Person("Chitra", 22),
        Person("Deepak", 28),
        Person("Esha", 26)
    )

    val ageMap = people.fold(mutableMapOf<String, Int>()) { acc, person ->
        acc[person.name] = person.age
        acc
    }
    println(ageMap) // Output: {Arjun=25, Bhaskar=30, Chitra=22, Deepak=28, Esha=26}
}

Output:

{Arjun=25, Bhaskar=30, Chitra=22, Deepak=28, Esha=26}

Conclusion

The fold function in Kotlin provides used for combining elements of a sequence into a single value by applying a binary operation, starting with an initial value. By understanding and using the fold function, you can efficiently aggregate and summarize data in your Kotlin applications, ensuring that you can perform complex calculations and data manipulations according to your requirements.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top