Kotlin List sumBy()
Syntax & Examples
Syntax of List.sumBy()
The syntax of List.sumBy() extension function is:
fun <T> Iterable<T>.sumBy(selector: (T) -> Int): Int
This sumBy() extension function of List returns the sum of all values produced by selector function applied to each element in the collection.
✐ Examples
1 Example
In this example,
- We create a list named
list
containing the integers1, 2, 3, 4, 5
. - We apply a selector function
{ it * it }
which squares each element of the list. - The
sumBy
function calculates the sum of all squared values. - The sum, which is an integer, is stored in
sum
. - Finally, we print the value of
sum
to standard output using theprintln
function.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf(1, 2, 3, 4, 5);
val sum = list.sumBy { it * it };
println(sum);
}
Output
55
2 Example
In this example,
- We create a list named
list
containing the strings"apple", "banana", "cherry", "date", "elderberry"
. - We apply a selector function
{ it.length }
which calculates the length of each string in the list. - The
sumBy
function calculates the sum of all lengths. - The sum, which is an integer, is stored in
sum
. - Finally, we print the value of
sum
to standard output using theprintln
function.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf("apple", "banana", "cherry", "date", "elderberry");
val sum = list.sumBy { it.length };
println(sum);
}
Output
31
3 Example
In this example,
- We define a data class
Person
with propertiesname
andage
. - We create a list named
people
containing instances ofPerson
. - We apply a selector function
{ it.age }
which extracts theage
property of eachPerson
object. - The
sumBy
function calculates the sum of all ages. - The sum, which is an integer, is stored in
sum
. - Finally, we print the value of
sum
to standard output using theprintln
function.
Kotlin Program
fun main(args: Array<String>) {
data class Person(val name: String, val age: Int)
val people = listOf(
Person("Alice", 30),
Person("Bob", 25),
Person("Charlie", 40)
);
val sum = people.sumBy { it.age };
println(sum);
}
Output
95
Summary
In this Kotlin tutorial, we learned about sumBy() extension function of List: the syntax and few working examples with output and detailed explanation for each example.