Kotlin Set sumByDouble()
Syntax & Examples


Set.sumByDouble() extension function

The sumByDouble() 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.sumByDouble()

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.

Parameters

ParameterOptional/RequiredDescription
selectorrequiredA function that takes an element and returns the value to be summed.

Return Type

Set.sumByDouble() returns value of type Double.



✐ Examples

1 Summing the lengths of strings in a set as Double

Using sumByDouble() to sum the lengths of strings in a set as Double.

For example,

  1. Create a set of strings.
  2. Use sumByDouble() with a selector function that returns the length of each string as Double.
  3. Print the resulting sum.

Kotlin Program

fun main() {
    val strings = setOf("one", "two", "three")
    val sum = strings.sumByDouble { it.length.toDouble() }
    println(sum)
}

Output

11.0

2 Summing the ages of people in a set of custom objects as Double

Using sumByDouble() to sum the ages of people in a set of custom objects as Double.

For example,

  1. Create a data class.
  2. Create a set of custom objects.
  3. Use sumByDouble() with a selector function that returns the age of each person as Double.
  4. 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.sumByDouble { it.age.toDouble() }
    println(sum)
}

Output

90.0

3 Summing the square roots of numbers in a set of integers

Using sumByDouble() to sum the square roots of numbers in a set of integers.

For example,

  1. Create a set of integers.
  2. Use sumByDouble() with a selector function that returns the square root of each number.
  3. Print the resulting sum.

Kotlin Program

fun main() {
    val numbers = setOf(1, 4, 9, 16)
    val sum = numbers.sumByDouble { Math.sqrt(it.toDouble()) }
    println(sum)
}

Output

10.0

Summary

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.