Kotlin

Kotlin Fold Examples

An all-purpose programming language with statically encoded data, Kotlin offers a variety of optional methods. The “fold” function in Kotlin is an effective higher-order method that lets you combine the items from an array into a single outcome. It cycles over the collection’s items, performing a combining function on each one and the present accumulated value before returning the outcome. It requires two parameters: an operation and a starting value.

The process of accretion is initiated from the initial value. A starting value and an action are required as inputs for the “fold” function. The operation specifies how each component is added to the current accumulated value, while the initial value indicates where the accumulation should start. The operation requires two inputs, the current element and the accumulated value, and it outputs the new accumulated value.

Kotlin Fold() Syntax:

Here is the syntax of the fold() function in Kotlin:

inline fun <T, R> Iterable<T>.fold(

  initial: R,

  operation: (acc: R, T) -> R

): R

Let’s break down the syntax of the Kotlin fold() function:

  • fold: It is the name of the method that accomplishes the folding operation.
  • <T>: It denotes the element type in the list that is being folded.
  • <R>: It denotes the type of the accumulated value and the output of the folding method.
  • Iterable<T>: It specifies the receiver type which represents that fold is an extension method for iterable lists.
  • initial: R: It is the initial value for the folding process. It represents the initial point of the accumulation.
  • operation: (acc: R, T) -> R: It is the merging method that takes two parameters: the accumulated value (acc) and the present element from the collection (T). The operation joins these two values to produce the updated accumulated value that is returned.
  • R: It denotes the return type of the fold method which is the concluding accumulated value.

Example 1:

To understand the overall working of Kotlin’s fold() function, we have to go through the code example in detail. Thus, in the given code, we have a Kotlin “main” function that demonstrates the usage of the “fold” function.

The code starts with the main() function declaration which starts with the curly brackets. The first line of the main() method declares and initializes a “ls” variable as a list of integers that contain the values 1, 2, 3, 4, 5, and 6. The very next line uses the fold function on the “ls” list. It invokes the “ls” list, and the initial value is set to 0. The following lambda expression { acc, n -> acc + n } defines the combining operation for the “fold” method. In this case, the lambda takes two parameters: “acc” represents the accumulated value and “n” represents the current element from the list.

The result is the new accumulated value. Lambda adds the recent “n” element to the accumulated “acc” value. The final result of the “fold” operation is added to the “Result” variable. In this situation, the “acc” value is “0” while the initial value is “1”, i.e. 0+1 =1. Then, the “acc” value becomes “1” and the next value becomes “2”, i.e. 1+2 = 3. This process continues until the last element of “6” is added to the most recent accumulated value.

In the end, the println(“Total: ” + Result) line prints the result of the “fold” operation. It concatenates the “Total: ” string with the value of the “Result” variable and prints it to the console.

fun main() {

val ls = listOf(1, 2, 3, 4, 5, 6)

val Result = ls.fold(0) {

  acc, n -> acc + n

}

println("Total: " + Result) // Output: 15

}

In this situation, the output is “Total: 21”.

Example 2:

Kotlin’s fold() function is not only specified for integer type values but it can be applied to the string values as well. Therefore, we will look into another Kotlin code example to demonstrate how we can make use of it. The following given code demonstrates the use of the “fold” function in Kotlin for strings and integers, separately.

The “listOf” function creates the “lw” list with the “val” keyword that contains three strings: “Ko”, “tl”, and “in”. Here comes the “fold” function that is applied to the “lw” list. The “fold” function takes an initial value of an empty string “” and a lambda expression { acc, w -> acc + ” ” + w } as its arguments. The lambda expression receives two parameters: “acc” represents the accumulated value and “w” represents each element of the “lw” list.

Inside the lambda, it concatenates the accumulated value with a space and the current “w” element. The result is allotted to the “s” variable. The “fold” function iterates over each element of the list, applying the lambda expression and updating the accumulated value.

In this case, it concatenates all the elements of the “lw” list with a space in between. The trim() function within the println() function prints the value of “s” after removing any leading or trailing whitespace using the trim function. This ensures that there are no extra spaces at the end and the start of the string. We create another list which is “ln” that contains five integers.

The very next line applies the “fold” function on the “ln” list. This time, the initial value is Int.MIN_VALUE which shows the smallest probable integer value. The lambda expression { acc, n -> if (n > acc) n else acc } compares the current element of “n” with the accumulated “acc” value. If “n” is greater than “acc”, it becomes the new accumulated value; otherwise, “acc” remains unchanged. This ensures that “mn” contains the largest number in the “ln” list. The println(“Largest Number: ” + mn) prints the “Largest Number: ” string that is concatenated with the value of “mn” which represents the largest number in the “ln” list.

fun main() {

val lw = listOf("Ko", "tl", "in")

val s = lw.fold("") { acc, w -> acc + " " + w }

println(s.trim())

val ln = listOf(18, 75, 56, 9, 67)

val mn = ln.fold(Int.MIN_VALUE) { acc, n -> if (n > acc) n else acc }

println("Largest Number: " +mn)

}

The first line of the output shows the use of the fold() function on the string list while the other line displays the output for the integer list.

Conclusion

The “fold” is an effective technique to aggregate the data, condense a collection to a single value, and carry out the intricate computations using a collection’s constituent pieces. Thus, we explained the syntax and code examples of using the fold() function in Kotlin. The examples covered the usage of Kotlin on integers as well as on string values.

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.