Kotlin List reduceRight()
Syntax & Examples
Syntax of List.reduceRight()
The syntax of List.reduceRight() extension function is:
fun <S, T : S> List<T>.reduceRight( operation: (T, acc: S) -> S ): S
This reduceRight() extension function of List accumulates value starting with the last element 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 the integers[1, 2, 3, 4, 5]
. - We use the
reduceRight
function to accumulate values starting with the last element. - In the
operation
,element
represents the current element, andacc
represents the accumulator value. - We subtract each element from the accumulator from right to left.
- Finally, we print the result to standard output using the
println
function.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf(1, 2, 3, 4, 5);
val result = list.reduceRight { element, acc -> acc - element };
println(result);
}
Output
-5
2 Example
In this example,
- We create a list named
list
containing the strings['apple', 'banana', 'cherry', 'date', 'elderberry']
. - We use the
reduceRight
function to accumulate values starting with the last element. - In the
operation
,element
represents the current element, andacc
represents the accumulator value. - We add each string to the accumulator from right to left.
- Finally, we print the result to standard output using the
println
function.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf("apple", "banana", "cherry", "date", "elderberry");
val result = list.reduceRight { element, acc -> acc + " " + element };
println(result);
}
Output
elderberry date cherry banana apple
Summary
In this Kotlin tutorial, we learned about reduceRight() extension function of List: the syntax and few working examples with output and detailed explanation for each example.