Kotlin Set sumOf()
Syntax & Examples
Set.sumOf() extension function
The sumOf() extension function in Kotlin returns the sum of all values produced by the selector function applied to each element in the collection.
Syntax of Set.sumOf()
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.
Parameters
Parameter | Optional/Required | Description |
---|---|---|
selector | required | A function that takes an element and returns the value to be summed. |
Return Type
Set.sumOf() returns value of type Double
.
✐ Examples
1 Summing the lengths of strings in a set as Double
Using sumOf() to sum the lengths of strings in a set as Double.
For example,
- Create a set of strings.
- Use sumOf() with a selector function that returns the length of each string as Double.
- Print the resulting sum.
Kotlin Program
fun main() {
val strings = setOf("one", "two", "three")
val sum = strings.sumOf { it.length.toDouble() }
println(sum)
}
Output
11.0
2 Summing the ages of people in a set of custom objects as Double
Using sumOf() to sum the ages of people in a set of custom objects as Double.
For example,
- Create a data class.
- Create a set of custom objects.
- Use sumOf() with a selector function that returns the age of each person as Double.
- Print the resulting sum.
Kotlin Program
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)
}
Output
90.0
3 Summing the square roots of numbers in a set of integers
Using sumOf() to sum the square roots of numbers in a set of integers.
For example,
- Create a set of integers.
- Use sumOf() with a selector function that returns the square root of each number.
- Print the resulting sum.
Kotlin Program
fun main() {
val numbers = setOf(1, 4, 9, 16)
val sum = numbers.sumOf { Math.sqrt(it.toDouble()) }
println(sum)
}
Output
10.0
Summary
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.