This article explores different ways to calculate the sum of all items in a List of Integers in Kotlin.

1. Using sum() function

A simple solution to calculate the sum of all elements in a List is calling the sum() function. It is available for a list of all numeric data types. i.e, Int, Long, Float, Double, Byte, Short.

Download Code

 
To get the sum of a specific field inside a list of objects, you can use the sumBy() function. If the field is a double, use the sumByDouble() function:

Download Code

 
Note that as of Kotlin 1.5, sumBy() function is deprecated. You should use the sumOf() function instead.

Download Code

 
Alternatively, you can transform each object of the element to the corresponding field using the map() function. Finally, return the sum using the sum() function. This is especially useful to convert and sum other data types.

Download Code

2. Reduce operation

Another viable alternative is to perform a reduce operation on the list, to get the sum of all elements in it. A typical implementation of this approach would look like:

Download Code

3. Using summaryStatistics() function

If you need other statistics about the list elements like min, max, average, etc., consider using the summaryStatistics() function of the primitive stream.

Download Code

4. Naive solution

Finally, you can calculate the sum of all elements in a List using a for-loop, as shown below:

Download Code

That’s all about calculating the sum of all items in a List of Integers in Kotlin.