Kotlin List foldRight()
Syntax & Examples
Syntax of List.foldRight()
The syntax of List.foldRight() extension function is:
fun <T, R> List<T>.foldRight( initial: R, operation: (T, acc: R) -> R ): R
This foldRight() extension function of List accumulates value starting with initial value and applying operation from right to left to each element and current accumulator value.
✐ Examples
1 Example
In this example,
- We create a list named
list
containing strings representing fruits. - We apply the
foldRight
function onlist
starting with the initial value"Fruits:"
. - The operation concatenates each fruit with the accumulator string
acc
. - The resulting string is printed to standard output.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf("apple", "banana", "cherry");
val result = list.foldRight("Fruits:") { fruit, acc -> "$acc $fruit" };
println(result);
}
Output
Fruits: cherry banana apple
2 Example
In this example,
- We create a list named
list
containing integers. - We apply the
foldRight
function onlist
starting with the initial value0
. - The operation accumulates the sum of all numbers.
- The resulting sum is printed to standard output.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf(10, 20, 30);
val result = list.foldRight(0) { number, acc -> acc + number };
println(result);
}
Output
60
3 Example
In this example,
- We create a list named
list
containing characters representing alphabets. - We apply the
foldRight
function onlist
starting with the initial value"Alphabets:"
. - The operation concatenates each character with the accumulator string
acc
. - The resulting string is printed to standard output.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf('a', 'b', 'c');
val result = list.foldRight("Alphabets:") { char, acc -> "$acc $char" };
println(result);
}
Output
Alphabets: c b a
Summary
In this Kotlin tutorial, we learned about foldRight() extension function of List: the syntax and few working examples with output and detailed explanation for each example.