Kotlin Array.sum() Tutorial
In Kotlin, the Array.sum()
function is used to calculate the sum of all elements in the given array. It is a concise way to obtain the total sum without the need for explicit iteration through the array elements.
This tutorial will explore the syntax of the sum()
function and provide examples of its usage in Kotlin arrays.
Syntax
The syntax of the sum()
function is as follows:
fun Array<out Byte>.sum(): Int
fun Array<out Short>.sum(): Int
fun Array<out Int>.sum(): Int
fun Array<out Long>.sum(): Long
fun Array<out Float>.sum(): Float
fun Array<out Double>.sum(): Double
fun Array<out UInt>.sum(): UInt
fun Array<out ULong>.sum(): ULong
fun Array<out UByte>.sum(): UInt
fun Array<out UShort>.sum(): UInt
Based on the values in the Array, the respective return type is considered.
Examples for Array sum() function
1. Using sum() with Array of integers
In this example, we’ll use the sum()
function with an IntArray
to calculate the sum of elements in an array of integers.
Kotlin Program
fun main() {
val numbersArray = arrayOf(10, 20, 30, 40, 50)
// Using sum() to calculate the sum of elements in the array
val sum = numbersArray.sum()
// Printing the original array and the result
println("Numbers Array:\n${numbersArray.contentToString()}\n")
println("Sum of Numbers:\n$sum")
}
Output
Numbers Array:
[10, 20, 30, 40, 50]
Sum of Numbers:
150
2. Using sum() with DoubleArray
In this example, we’ll use the sum()
function with an array of Double
elements to calculate the sum of elements in an array of doubles.
Kotlin Program
fun main() {
val doublesArray = arrayOf(1.5, 2.5, 3.5, 4.5, 5.5)
// Using sum() to calculate the sum of elements in the array
val sum = doublesArray.sum()
// Printing the original array and the result
println("Given Array:\n${doublesArray.contentToString()}\n")
println("Sum of Numbers:\n$sum")
}
Output
Given Array:
[1.5, 2.5, 3.5, 4.5, 5.5]
Sum of Numbers:
17.5
Summary
In this tutorial, we’ve covered the sum()
function in Kotlin arrays, its syntax, and how to use it to calculate the sum of array elements.