Kotlin Array - reduceRight() Function



The Kotlin array reduceRight() function is used to accumulate or combine all elements of an array to a single value, starting with the last element, using a binary operation, specified by a lambda function.

This function applies operation from right to left to each element and current accumulator value.

Exception

If an array is empty this function will throw an "UnsupportedOperationException".

Syntax

Following is the syntax of Kotlin array reduceRight() function −

inline fun <S, T : S> Array<out T>.reduceRight(
   operation: (T, acc: S) -> S
): S

Parameters

This function accepts an operation represent a current accumulator value and an element, and calculates the next accumulator value.

Return value

This function returns a single value of the same type as the element of an array.

Example 1

The following is a basic example to demonstrate the use of reduceRight() function −

fun main(args: Array<String>) {
   val numbers = arrayOf(1, 2, 3, 4, 5, 6)
   val sum = numbers.reduceRight { num, acc -> acc + num }
   println("Sum of elements: $sum")
}

Output

The above code generate following output −

Sum of elements: 21

Example 2

The below example, creates an array and accumulating all elements into a single value using reduceRight() function −

fun main(args: Array<String>) {
   val strings = arrayOf<String>("a", "b", "c", "d", "e")
   val res = strings.reduceRight{ string, acc -> acc + string }
   println("Single value: $res")
}

Output

Following is the output −

Single value: edcba

Example 3

Let's see another example. What will be the output if we use reduceRight() function and an array is empty −

fun main(args: Array<String>) {
   val numbers = arrayOf<Int>()
   val sum = numbers.reduceRight { num, acc -> acc + num }
   println("Sum of elements: $sum")
}

Output

The above code throw an exception if an array is empty −

Exception in thread "main" java.lang.UnsupportedOperationException: Empty array can't be reduced.
kotlin_arrays.htm
Advertisements