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 integers 1, 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 the println 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 the println function.

Kotlin Program

fun main(args: Array<String>) {
    val list = listOf(&quot;apple&quot;, &quot;banana&quot;, &quot;cherry&quot;, &quot;date&quot;, &quot;elderberry&quot;);
    val sum = list.sumBy { it.length };
    println(sum);
}

Output

31

3 Example

In this example,

  • We define a data class Person with properties name and age.
  • We create a list named people containing instances of Person.
  • We apply a selector function { it.age } which extracts the age property of each Person 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 the println function.

Kotlin Program

fun main(args: Array<String>) {
    data class Person(val name: String, val age: Int)
    val people = listOf(
        Person(&quot;Alice&quot;, 30),
        Person(&quot;Bob&quot;, 25),
        Person(&quot;Charlie&quot;, 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.