Kotlin Array - sumOf() Function



The Kotlin array sumOf() function is used to return the sum of array elements produced by selector function applied to each element in the array.

This function can be invoked on arrays of integers, floating-point number, and other numeric types. It will not work with String or Character data types.

The sumBy() function has been deprecated in the latest version of Kotlin. It is recommended to replace sumBy() with the sumOf() function.

Syntax

Following is the syntax of Kotlin array sumOf() function −

fun <T> Array<out T>.sumOf(selector: (T) -> Int): Int

Parameters

This function accepts selector as a parameters.

Return value

This function returns sum of all values specified by selector function.

Example 1

Following is a basic example to demonstrate the use of sumOf() function −

fun main(args: Array<String>){
   var arr = arrayOf(3, 4, 5, 6)
   print("Array elements: ")
   println(arr.joinToString())

   // Sum of all element of an array
   val total = arr.sumOf({it})
   println("Sum of array's element: "+ total)
}

Output

The above code generate following output −

Array elements: 3, 4, 5, 6
Sum of array's element: 18

Example 2

Let's see another example. Here, we use the sumOf function to calculate the sum of element with their double value −

fun main(args: Array<String>){
   var arr = arrayOf(1, 2, 3, 4, 5)
   println("Array elements: ")
   arr.forEach { println(it) }

   //Sum of all element with their double value
   println("Sum of array's element ${arr.sumOf{it*2}}")
}

Output

Following is the output −

Array elements: 
1
2
3
4
5
Sum of array's element 30

Example 3

Let's see below example where we have an array of Product objects, and we want to calculate the total price of all products using sumOf() function −

data class Product(val name: String, val price: Double, val quantity: Int)

fun main(args: Array<String>) {
   val products = arrayOf(
      Product("Laptop", 999.99, 1),
      Product("Mouse", 19.99, 2),
      Product("Keyboard", 49.99, 1),
      Product("Monitor", 199.99, 2)
   )
   // Calculate the total price of all products
   val totalPrice = products.sumOf { it.price * it.quantity }

   // Display the result
   println("The total price of all products is: $$totalPrice")
}

Output

The above code produce following output −

The total price of all products is: $1489.94
kotlin_arrays.htm
Advertisements