Kotlin

Kotlin Reduce Examples

Kotlin’s reduce is a higher-order function that operates on collections and allows you to iteratively combine the elements of a collection into a single result. It applies a specified operation to each element in the collection, using the result of the previous operation as an input for the next element. The final value that is given by reduce indicates what happens when all of the collection’s items are combined using the particular operation. It can be of the same type as the elements in the collection or a different type, depending on the operation and the initial value provided. In this guide today, we will show you some code examples to demonstrate the working of the “reduce” function in Kotlin.

Syntax:

A starting value and a lambda method are the two arguments that are needed for the reduction function. The beginning value serves as the point at which the reduction process is initiated, and the lambda function specifies the action to be carried out on every single element. As reduce traverses the collection, it applies the lambda function to the accumulator and the current element, producing a new value. This new value becomes the accumulator for the next iteration.

The procedure keeps on until a final value is produced after all of the collection’s items are analyzed. The given syntax represents a declaration of an “inline” function in the Kotlin programming language. Let’s break it down and explain each part:

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

Inline fun: This indicates the start of the function declaration and specifies that the function will be inlined. Inlining means that the function’s code is inserted directly at the call site, potentially improving the performance.

<T>: This is a generic type parameter declaration where “T” represents a type parameter that can be replaced with any specific type at the call site. It enables the function to operate on many data kinds.

Iterable<T>: This is the receiver type of the function which indicates that this function is an extension function on the Iterable interface. It means that any object of a class that implements the Iterable interface can call this function.

.reduce: This is the name of the function that is being declared. It represents a higher-order function that is used to reduce the elements of the Iterable into a single value.

(operation: (acc: T, T) -> T): This is the parameter declaration for the reduce function. It takes a single parameter named “operation” which is a function itself. The operation function accepts two parameters of type “T” (the generic type of the Iterable) and returns a value of type “T”. It represents the operation to be applied on each pair of elements during the reduction process.

: T: This is the return type of the reduce function which indicates that the result of the reduction process is of type “T”.

Example 1:

In Kotlin, the reduction method is an extension method that is specified on the Iterable type. It acts on each element in the collection iteratively until only one value remains. This functionality is discovered using the following Kotlin code example.

The first line declares a new immutable list “nl” and initializes it with a list of integers that contains the values 1, 2, 3, 4, and 5 using the “listOf” function. Here, a new variable “add” is declared and assigned with the result of calling the “reduce” function on the “nl” list.

In this case, the reduction operation is defined using a lambda expression { acc, n -> acc + n }, which takes two parameters: “acc” (short for “accumulator”) and “n” (the current element being processed). The lambda expression specifies that the accumulator should be incremented by the current element. The println(“Sum of all numbers in List: ” + add) line uses the “println” function to print a string to the console.

The string is composed of a fixed text message (“Sum of all numbers in List: “) that is concatenated with the value of the “add” variable which represents the sum of all the numbers in the list. The “+” operator is used for string concatenation.

fun main() {

  val nl = listOf(1, 2, 3, 4, 5)

  val add = nl.reduce { acc, n -> acc + n }

  println("Sum of all numbers in List: " +add)

}

The output for the previous code example is displayed in the following which outputs the sum of “15” of all the integer values of an immutable list:

Example 2:

Here’s another code example of Kotlin that uses the “reduce” function to find the maximum value in a list of numbers (10, 5, 7, 15, 3). The very first line declares and initializes an immutable list called “nl” with the [10, 5, 7, 15, 3] values. It represents a collection of integers. The second line declares and initializes the “m:” variable by calling the “reduce” function on the “nl” list. The “reduce” function iterates over the elements of the list and reduces them to a single value.

The lambda expression { acc, n -> if (n > acc) n else acc } is used here. It is a “lambda” function that serves as the operation for the reduction process. It takes two parameters: “acc” represents the accumulated value and “n” indicates that the element is under consideration at the moment. The lambda yields a value that is bigger when comparing each element to the total value (acc). This way, it effectively finds the maximum value in the list. The println(m) line prints the value of “m” which signifies the end of the reduction process, the maximum value in the list.

fun main() {

  val nl = listOf(10, 5, 7, 15, 3)

  val m = nl.reduce { acc, n -> if (n > acc) n else acc }

  println("Max Value: " +m)

}

To summarize, the code creates a list of integers, and then the “reduce” function is used with a lambda operation to find the maximum value in the list. The “m” variable holds the highest value which is subsequently shown using “println” as seen in the following:

Conclusion

Kotlin’s “reduce” function is a powerful function that allows you to perform the iterative calculations on a collection, progressively combining its elements into a single result using a specified operation. The “reduce” function assumes that the collection is not empty, which is critical to know. An error is thrown if you try to apply “reduce” on a blank collection. Kotlin has the “reduceOrNull” method to deal with empty collections which yields a null rather than raising an error when used on a blank collection.

About the author

Saeed Raza

Hello geeks! I am here to guide you about your tech-related issues. My expertise revolves around Linux, Databases & Programming. Additionally, I am practicing law in Pakistan. Cheers to all of you.