
- Kotlin - Home
- Kotlin - Overview
- Kotlin - Environment Setup
- Kotlin - Architecture
- Kotlin - Basic Syntax
- Kotlin - Comments
- Kotlin - Keywords
- Kotlin - Variables
- Kotlin - Data Types
- Kotlin - Operators
- Kotlin - Booleans
- Kotlin - Strings
- Kotlin - Arrays
- Kotlin - Ranges
- Kotlin - Functions
- Kotlin Control Flow
- Kotlin - Control Flow
- Kotlin - if...Else Expression
- Kotlin - When Expression
- Kotlin - For Loop
- Kotlin - While Loop
- Kotlin - Break and Continue
- Kotlin Collections
- Kotlin - Collections
- Kotlin - Lists
- Kotlin - Sets
- Kotlin - Maps
- Kotlin Objects and Classes
- Kotlin - Class and Objects
- Kotlin - Constructors
- Kotlin - Inheritance
- Kotlin - Abstract Classes
- Kotlin - Interface
- Kotlin - Visibility Control
- Kotlin - Extension
- Kotlin - Data Classes
- Kotlin - Sealed Class
- Kotlin - Generics
- Kotlin - Delegation
- Kotlin - Destructuring Declarations
- Kotlin - Exception Handling
Kotlin Array - reduce() Function
The Kotlin array reduce() function is used to accumulate or combine all elements of an array to a single value, starting with the first element, using a binary operation, specified by a lambda function.
This function applies operation from left to right to current accumulator value and each element.
Exception
If an array is empty this function will throw an "UnsupportedOperationException".
Syntax
Following is the syntax of Kotlin array reduce() function −
inline fun <S, T : S> Array<out T>.reduce( operation: (acc: S, T) -> 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 list containing successive accumulation values generated by applied operation.
Example 1
The following is a basic example to demonstrate the use of reduce() function −
fun main(args: Array<String>) { val numbers = arrayOf(1, 2, 3, 4, 5) val sum = numbers.reduce { acc, num -> acc + num } println("Sum of elements: $sum") }
Output
The above code generate following output −
Sum of elements: 15
Example 2
Let's see another example. What will be the output if we use reduce() function and an array is empty −
fun main(args: Array<String>) { val numbers = arrayOf<Int>() val exec = numbers.reduce { acc, num -> acc } println("Single value: $exec") }
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.
Example 3
The below example, creates an array and accumulating all elements into a single value using reduce() function −
fun main(args: Array<String>) { val strings = arrayOf<String>("a", "b", "c", "d", "e") val res = strings.reduce { acc, string -> acc + string } println("Single value: $res") }
Output
Following is the output −
Single value: abcde