Kotlin Array - sum() Function



The Kotlin array sum() function is used to calculate the sum of all elements in an array of numeric type.

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.

Syntax

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

fun Array<out Numeric_type>.sum(): Numeric_type

Parameters

This function does not accepts any parameters.

Return value

This function returns sum of all elements of an array.

Example 1

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

fun main(args: Array<String>) {
   val array = arrayOf<Int>(1, 2, 3, 4, 5)

   // sum of array's element
   val total = array.sum()

   // Display result
   println("sum of array: $total")
}

Output

The above code generate following output −

sum of array: 15

Example 2

Another example of using the sum function, with an array of floating-point numbers −

fun main(args: Array<String>) {
   val prices = doubleArrayOf(19.99, 5.49, 12.99, 3.50, 7.25)

   // Calculate the sum of the array elements
   val totalCost = prices.sum()

   // Display the result
   println("The total cost of the items is: $totalCost")
}

Output

Following is the output −

After sumed: [Daisy, Rose, Sunflower]

Example 3

Let's see what will happen if we use the sum function in an array of string type −

fun main(args: Array<String>) {
   val prices = arrayOf<String>("tutorialspoint", "India")

   // Calculate the sum of the array elements
   val totalCost = prices.sum()

   // Display the result
   println("Sum of string: $totalCost")
}

Output

The above code produce an error if we use an array of string −

None of the following candidates is applicable: @JvmName(...) fun Array<out Byte>.sum(): Int @JvmName(...) fun Array<out Double>.sum():  ...
kotlin_arrays.htm
Advertisements