Kotlin Array.fold() function
In Kotlin, the Array.fold()
function is used to accumulate the elements of an array into a single result by applying a given operation sequentially along with the elements and the current accumulator value.
This function is useful when you need to perform a cumulative operation on the elements of an array, such as calculating a sum or product.
In this tutorial, we shall learn the syntax and go through some examples of Kotlin Array.fold()
function.
Syntax
The syntax of the Array fold()
function is:
inline fun <T, R> Array<out T>.fold(
initial: R,
operation: (acc: R, T) -> R
): R
where
Parameter | Description |
---|---|
initial | The initial value of the accumulator. |
operation | The operation to perform on each element, taking the current accumulator value and the element as parameters, and returning the updated accumulator value. |
You can call fold() function on an Array, ByteArray, ShortArray, IntArray, LongArray, FloatArray, DoubleArray, BooleanArray, and CharArray objects.
Examples for Array.fold()
1. Using Array.fold() to calculate the sum of elements in an Array
In this example, we’ll use fold()
to calculate the sum of elements in a list of numbers.
Kotlin Program
fun main() {
val numbersArray = arrayOf(10, 20, 30, 40, 50)
// Using fold() to calculate the sum
val sum = numbersArray.fold(0) { acc, number ->
acc + number
}
// Printing the original array and the result
println("Array\n${numbersArray.contentToString()}\n")
println("Sum of Array Elements\n$sum")
}
In this example, the fold()
function is used to calculate the sum of numbers in a list. The initial accumulator value is set to 0, and the operation adds each element to the accumulator.
Output
Array
[10, 20, 30, 40, 50]
Sum of Array Elements
150
Summary
In this tutorial, we’ve covered the Array.fold()
function in Kotlin, explaining its syntax and providing an example of calculating the sum of elements in a collection.