Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

sumof
kotlin
list
communitycreator

How to use the sumOf method of List in Kotlin

Programming Bytes

Overview

The sumOf method of List applies the provided selector function on each element and returns the sum of the values returned by the selector function for each element of the List.

Syntax

@JvmName("sumOfInt") inline fun <T> Iterable<T>.sumOf(
    selector: (T) -> Int
): Int

Note: This method has multiple syntaxes for different data types. Please click here to learn more.

Parameters

This method takes an inline function (selector) as an argument.

Return value

This method returns the sum of all values produced by the selector function applied on each element.

Example

The code below demonstrates how to use the sumOf method in Kotlin.

fun main() {
  //create a list with int elements elements 
  val list:List<Int> = listOf(1,2,3)
  println("\nlist : ${list}")

  var sum = list.sumOf{it*2}
  println("Sum of all elements after multiplyying each element by 2 : ${sum}")

  sum = list.sumOf{it * it}
  println("Sum of all elements after square each element : ${sum}")
}
Using the sumOf method

Explanation

Line 3: We create a List with the name list using the listOf method. The list will have three elements 1,2,3.

Line 6: We use the sumOf method with a selector function. The selector function multiplies the element by 2 and returns it. In our case, the selector function returns:

  • For the element 1, 2 is returned.
  • For the element 2, 4 is returned.
  • For the element 3, 6 is returned.

The above values are summed and returned as a result. The result is 12.

Line 9: We use the sumOf method with a selector function. The selector function squares the element and returns it. In our case, the selector function returns:

  • For the element 1, 1 is returned.
  • For the element 2, 4 is returned.
  • For the element 3, 9 is returned.

The above values are summed and returned as a result. The result is 14.

RELATED TAGS

sumof
kotlin
list
communitycreator
RELATED COURSES

View all Courses

Keep Exploring