This post will discuss how to calculate the sum of all elements in an array in Kotlin.

1. Using sum() function

You can easily get the sum of all elements in the array using the sum() function. It is available for arrays of Int, Double, Float, Long, Short, Byte.

Download Code

 
The following code example demonstrates the usage of the sum() function for a “typed” array.

Download Code

 
Another alternative is to use reduction to perform the addition, as shown below:

Download Code

2. Using SummaryStatistics

If you don’t mind using the Java Stream API, you can get the sum of all array elements using the summaryStatistics() function. You can also use it to get other stats like min, max, count, and average. A typical invocation for this function would look like:

Download Code

 
The following example demonstrates its usage for a “typed” array.

Download Code

Finally, you can always iterate over the array using the for loop and accumulate the sum of all elements. That’s all about calculating the sum of all elements in an array in Kotlin.