The sumOf() extension function in Kotlin returns the sum of all values produced by the selector function applied to each element in the collection.
The syntax of Set.sumOf() extension function is:
fun <T> Set<T>.sumOf(selector: (T) -> Double): Double
This sumOf() extension function of Set returns the sum of all values produced by selector function applied to each element in the collection.
Parameter | Optional/Required | Description |
---|---|---|
selector | required | A function that takes an element and returns the value to be summed. |
Set.sumOf() returns value of type Double
.
Using sumOf() to sum the lengths of strings in a set as Double.
For example,
fun main() {
val strings = setOf("one", "two", "three")
val sum = strings.sumOf { it.length.toDouble() }
println(sum)
}
11.0
Using sumOf() to sum the ages of people in a set of custom objects as Double.
For example,
data class Person(val name: String, val age: Int)
fun main() {
val people = setOf(Person("Alice", 30), Person("Bob", 25), Person("Charlie", 35))
val sum = people.sumOf { it.age.toDouble() }
println(sum)
}
90.0
Using sumOf() to sum the square roots of numbers in a set of integers.
For example,
fun main() {
val numbers = setOf(1, 4, 9, 16)
val sum = numbers.sumOf { Math.sqrt(it.toDouble()) }
println(sum)
}
10.0
In this Kotlin tutorial, we learned about sumOf() extension function of Set: the syntax and few working examples with output and detailed explanation for each example.