The sumBy() 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.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.
Parameter | Optional/Required | Description |
---|---|---|
selector | required | A function that takes an element and returns the value to be summed. |
Set.sumBy() returns value of type Int
.
Using sumBy() to sum the lengths of strings in a set.
For example,
fun main() {
val strings = setOf("one", "two", "three")
val sum = strings.sumBy { it.length }
println(sum)
}
11
Using sumBy() to sum the ages of people in a set of custom objects.
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.sumBy { it.age }
println(sum)
}
90
Using sumBy() to sum the squares of numbers in a set of integers.
For example,
fun main() {
val numbers = setOf(1, 2, 3, 4)
val sum = numbers.sumBy { it * it }
println(sum)
}
30
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.