How to Find Sum of List in Kotlin: Simple Guide
To find the sum of a list in Kotlin, use the
sum() function directly on the list of numbers. For example, val total = listOf(1, 2, 3).sum() calculates the sum of the list elements.Syntax
The sum() function is called on a list of numbers to get their total sum.
listOf(...): Creates a list of numbers..sum(): Adds all numbers in the list and returns the total.val total: Stores the sum result.
kotlin
val total = listOf(1, 2, 3, 4, 5).sum()
Example
This example shows how to create a list of integers and find their sum using sum(). It prints the total sum to the console.
kotlin
fun main() {
val numbers = listOf(10, 20, 30, 40)
val total = numbers.sum()
println("Sum of the list is: $total")
}Output
Sum of the list is: 100
Common Pitfalls
One common mistake is trying to use sum() on a list of non-numeric types like strings, which will cause an error. Also, using sum() on an empty list returns 0, which is expected but good to remember.
For lists of other numeric types like Double or Float, use sum() as well, but ensure the list type matches.
kotlin
/* Wrong: sum() on list of strings causes error */ // val words = listOf("a", "b", "c") // val total = words.sum() // Error: Unresolved reference /* Right: sum() on list of integers */ val numbers = listOf(1, 2, 3) val total = numbers.sum()
Quick Reference
| Function | Description |
|---|---|
| sum() | Returns the sum of all elements in a numeric list. |
| sumBy(selector) | Sums values returned by selector function (deprecated, use sumOf). |
| sumOf(selector) | Sums values returned by selector function, supports transformations. |
Key Takeaways
Use the built-in
sum() function to get the total of a numeric list in Kotlin.Ensure the list contains numeric types like Int, Double, or Float before calling
sum().Calling
sum() on an empty list returns 0 without errors.For custom calculations, use
sumOf() with a selector function.Avoid using
sum() on non-numeric lists to prevent errors.