Kotlin String reduce()

Kotlin String reduce() Tutorial

The String.reduce() function in Kotlin is used to apply a binary operation to the characters of the string sequentially, reducing them to a single result. It takes an operation function that defines how the characters are combined, and it returns the final result.

In this tutorial, we’ll explore the syntax of the reduce() function and provide examples of its usage in Kotlin strings.

Syntax

The syntax of the reduce() function is as follows:

inline fun CharSequence.reduce(
    operation: (acc: Char, Char) -> Char
): Char

where

ParameterDescription
operationA function that defines the binary operation to be applied to the characters. It takes an accumulator acc and the current character, and returns a new accumulator value.
Parameter of String.reduce() function

The operation parameter is a function that specifies how the characters are combined. It takes two parameters: the accumulator acc and the current character. The function returns a new accumulator value.

Examples for String reduce() function

1. Find Maximum Character in the given String

In this example, we’ll use reduce() to find the maximum character (based on Unicode values) in a given string.

  1. Take a string value in text.
  2. Define an operation function that compares the accumulator and the current character and returns the greater of the two.
  3. Call reduce() function on text with the operation function as an argument. The function finds the maximum character and returns it.
  4. You may print the original string and the resulting maximum character to the console output.

Kotlin Program

fun main() {
    val text = "Hello World"

    // Defining an operation to find the maximum character
    val operation: (acc: Char, Char) -> Char = { acc, char -> if (acc > char) acc else char }

    // Using reduce() to find the maximum character and return it
    val resultChar = text.reduce(operation)

    // Printing the original string and the resulting maximum character
    println("Original String:\n$text\n")
    println("Maximum Character:\n$resultChar")
}

Output

Original String:
Hello World

Maximum Character:
r

Summary

In this tutorial, we’ve covered the reduce() function in Kotlin strings, its syntax, and how to use it to apply a binary operation to the characters of a string sequentially, resulting in a single value. This function is versatile and can be used for various operations such as concatenation, finding maximum values, and more.