The sumByDouble() 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.sumByDouble() extension function is:
fun <T> Set<T>.sumByDouble(selector: (T) -> Double): Double
This sumByDouble() 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.sumByDouble() returns value of type Double
.
Using sumByDouble() to sum the lengths of strings in a set as Double.
For example,
fun main() {
val strings = setOf("one", "two", "three")
val sum = strings.sumByDouble { it.length.toDouble() }
println(sum)
}
11.0
Using sumByDouble() 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.sumByDouble { it.age.toDouble() }
println(sum)
}
90.0
Using sumByDouble() 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.sumByDouble { Math.sqrt(it.toDouble()) }
println(sum)
}
10.0
In this Kotlin tutorial, we learned about sumByDouble() extension function of Set: the syntax and few working examples with output and detailed explanation for each example.