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

ParameterOptional/RequiredDescription
selectorrequiredA 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,

  1. Create a set of strings.
  2. Use sumOf() 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.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,

  1. Create a data class.
  2. Create a set of custom objects.
  3. Use sumOf() 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.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,

  1. Create a set of integers.
  2. Use sumOf() 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.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.