Kotlin Array average()

Kotlin Array average()

In Kotlin, the Array average() function is used to calculate the average of numeric elements in this array. It provides a convenient way to obtain the mean value of the elements.

This function is particularly useful when dealing with arrays containing numerical data, such as integers or floating-point numbers.

In this tutorial, we’ll explore the syntax of the average() function and provide examples of its usage in Kotlin arrays.

Syntax

The syntax of the average() function is:

fun Array<out Byte>.average(): Double
fun Array<out Short>.average(): Double
fun Array<out Int>.average(): Double
fun Array<out Long>.average(): Double
fun Array<out Float>.average(): Double
fun Array<out Double>.average(): Double

The average() function returns the average value of the elements as a Double.

Examples for Array average() function

1. Using average() to Calculate the Average Temperature

In this example, we’ll use average() to calculate the average temperature from an array of temperature values.

Kotlin Program

fun main() {
    val temperaturesArray = arrayOf(22.5, 24.0, 21.8, 23.2, 25.5)
    
    // Using average() to calculate the average temperature
    val averageTemperature = temperaturesArray.average()
    
    // Printing the original array and the result
    println("Temperatures: ${temperaturesArray.joinToString(", ")}")
    println("Average Temperature: $averageTemperature")
}

Output

Temperatures: 22.5, 24.0, 21.8, 23.2, 25.5
Average Temperature: 23.4

2. Using average() to Calculate Average Word Length

In this example, we’ll use average() to calculate the average length of words in a String array.

Kotlin Program

fun main() {
    val wordsArray = arrayOf("apple", "banana", "cherry", "guava")

    // Using average() to calculate the average word length
    val averageWordLength = wordsArray.map { it.length }.average()

    // Printing the original array and the result
    println("Words: ${wordsArray.joinToString(", ")}")
    println("Average Word Length: $averageWordLength")
}

Output

Words: apple, banana, cherry, guava
Average Word Length: 5.5

Summary

In this tutorial, we’ve covered the average() function in Kotlin arrays, its syntax, and how to use it to calculate the average of numeric elements.