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
.
@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.
This method takes an inline function (selector
) as an argument.
This method returns the sum of all values produced by the selector
function applied on each element.
The code below demonstrates how to use the sumOf
method in Kotlin
.
fun main() {//create a list with int elements elementsval 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}")}
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:
1
, 2
is returned.2
, 4
is returned.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:
1
, 1
is returned.2
, 4
is returned.3
, 9
is returned.The above values are summed and returned as a result. The result is 14
.