Kotlin List runningFold()
Syntax & Examples
Syntax of List.runningFold()
The syntax of List.runningFold() extension function is:
fun <T, R> Iterable<T>.runningFold( initial: R, operation: (acc: R, T) -> R ): List<R>
This runningFold() extension function of List returns a list containing successive accumulation values generated by applying operation from left to right to each element and current accumulator value that starts with initial value.
✐ Examples
1 Example
In this example,
- We create a list of integers named
list
containing elements1, 2, 3, 4, 5
. - We use the
runningFold
function to apply addition from left to right starting with an initial value of0
. - The resulting list of accumulated values is stored in
result
. - We print
result
usingprintln()
.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf(1, 2, 3, 4, 5)
val result = list.runningFold(0) { acc, element -> acc + element }
println(result)
}
Output
[0, 1, 3, 6, 10, 15]
2 Example
In this example,
- We create a list of strings named
list
containing elements"apple", "banana", "cherry"
. - We use the
runningFold
function to concatenate strings from left to right starting with an empty string''
. - The resulting list of accumulated strings is stored in
result
. - We print
result
usingprintln()
.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf("apple", "banana", "cherry")
val result = list.runningFold("") { acc, element -> acc + element }
println(result)
}
Output
[, apple, applebanana, applebananacherry]
Summary
In this Kotlin tutorial, we learned about runningFold() extension function of List: the syntax and few working examples with output and detailed explanation for each example.