Kotlin List sumOf()
Syntax & Examples


Syntax of List.sumOf()

The syntax of List.sumOf() extension function is:

fun <T> Iterable<T>.sumOf(selector: (T) -> Double): Double

This sumOf() 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 of doubles named list1 with elements 1.5, 2.7, 3.9, 4.1.
  • We apply the sumOf function on list1 using a selector that doubles each element.
  • The result is the sum of all doubled elements, which is 24.4.
  • We print the result using println().

Kotlin Program

fun main(args: Array<String>) {
    val list1 = listOf(1.5, 2.7, 3.9, 4.1)
    val result = list1.sumOf { it * 2 }
    println(result)
}

Output

24.4

2 Example

In this example,

  • We create a list of characters named list1 with elements 'a', 'b', 'c', 'd'.
  • We convert each character to its ASCII value as double using toInt().toDouble() in the selector function.
  • We apply the sumOf function on list1 using this selector.
  • The result is the sum of ASCII values of characters, which is 394.0.
  • We print the result using println().

Kotlin Program

fun main(args: Array<String>) {
    val list1 = listOf('a', 'b', 'c', 'd')
    val result = list1.sumOf { it.toInt().toDouble() }
    println(result)
}

Output

394.0

3 Example

In this example,

  • We create a list of strings named list1 with elements "apple", "banana", "cherry", "date".
  • We apply the sumOf function on list1 using a selector that calculates the length of each string as a double.
  • The result is the sum of lengths of all strings, which is 21.0.
  • We print the result using println().

Kotlin Program

fun main(args: Array<String>) {
    val list1 = listOf("apple", "banana", "cherry", "date")
    val result = list1.sumOf { it.length.toDouble() }
    println(result)
}

Output

21.0

Summary

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