Sobes.tech
Junior — Middle

How can you calculate the total sum of all values contained in a list using Kotlin?

sobes.tech AI

Answer from AI

In Kotlin, to calculate the sum of all values in a list, you can use the sum() function or sumBy/sumOf for lists with objects or computed values.

Example for a list of integers:

val numbers = listOf(1, 2, 3, 4, 5)
val total = numbers.sum()
println(total) // Outputs 15

If the list contains objects and you need to sum a specific field, you can use sumOf:

data class Item(val price: Double)

val items = listOf(Item(10.5), Item(20.0), Item(5.5))
val totalPrice = items.sumOf { it.price }
println(totalPrice) // Outputs 36.0

Thus, to calculate the total sum, simply call the appropriate summing function.

How can you calculate the total sum of all values… - sobes.tech