Kotlin Set sumBy()
Syntax & Examples


Set.sumBy() extension function

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

The syntax of Set.sumBy() extension function is:

fun <T> Set<T>.sumBy(selector: (T) -> Int): Int

This sumBy() 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.sumBy() returns value of type Int.



✐ Examples

1 Summing the lengths of strings in a set

Using sumBy() to sum the lengths of strings in a set.

For example,

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

Kotlin Program

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

Output

11

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

Using sumBy() to sum the ages of people in a set of custom objects.

For example,

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

Output

90

3 Summing the squares of numbers in a set of integers

Using sumBy() to sum the squares of numbers in a set of integers.

For example,

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

Kotlin Program

fun main() {
    val numbers = setOf(1, 2, 3, 4)
    val sum = numbers.sumBy { it * it }
    println(sum)
}

Output

30

Summary

In this Kotlin tutorial, we learned about sumBy() extension function of Set: the syntax and few working examples with output and detailed explanation for each example.