How do I sum all the items of a list of integers in Kotlin?

You can use the .sum() function to sum all the elements in an array or collection of Byte, Short, Int, Long, Float or Double. (docs)

For example:

val myIntList = listOf(3, 4, 2)
myIntList.sum() // = 9

val myDoubleList = listOf(3.2, 4.1, 2.0)
myDoubleList.sum() // = 9.3

If the number you want to sum is inside an object, you can use sumOf to select the specific field you want to sum: (docs)

data class Product(val name: String, val price: Int)
val products = listOf(Product("1", 26), Product("2", 44))
val totalCost  = products.sumOf { it.price } // = 70

Note: sumBy was deprecated in Kotlin 1.5 in favour of sumOf.

Leave a Comment

File not found.