기본 숫자형 컬렉션의 모든 요소를 합한다. (ex: List<Int>, List<Double>, List<Long> 등)
val numbers = listOf(1, 2, 3, 4, 5)
val total = numbers.sum()
println(total) // 출력: 15
각 요소에 조건을 적용한 후 그 결과를 합한다.
val people = listOf(
Person("Alice", 30),
Person("Bob", 25),
Person("Charlie", 35)
)
val totalAge = people.sumOf { it.age } // 각 요소의 age 속성을 합산
println(totalAge) // 출력: 90
숫자형 뿐 아니라, 각 요소의 특정 속성이나 변환된 결과를 더할 수 있다.
val words = listOf("a", "ab", "abc")
val totalLength = words.sumOf { it.length } // 각 단어의 길이를 합산
println(totalLength) // 출력: 6