Handling division by zero exception in average calculation for empty lists

Advertisements

I am trying to implement a function in Kotlin that returns the average of a list of numbers. The function should take a list of integers as an argument and return the average of all the elements in the list.

Here’s what I have so far (with an example):

fun getAverage(nums: List<Int>): Double{
    return (nums.sum().toDouble() / nums.size)
}

val numbers = listOf(1, 2, 3, 4, 5)
val newList = getAverage(numbers)

This code works fine for lists with a non-zero number of elements, but it throws a division by zero exception for empty lists. How can I modify the function to handle empty lists gracefully and return a default value, such as 0, in that case?

Keep in mind, I do not want a predefined function, I want to implement my own, so in the future I will be able to customize it as I please

>Solution :

Just use an if (In Kotlin, you can use ifs as expressions yielding the last value):

fun getAverage(nums: List<Int>): Double{
    return
        if (nums.isEmpty())
            0.0
        else
            (nums.sum().toDouble() / nums.size)
}

This can be written in a more compact way using

fun getAverage(nums: List<Int>) = if (nums.isEmpty()) 0.0 else (nums.sum().toDouble() / nums.size)

In that case, getAverage(listOf()) will return 0.0.

Alternatively, you could also make the result nullable and return null in that case:

fun getAverage(nums: List<Int>): Double?{
    return
        if (nums.isEmpty())
            null
        else
            (nums.sum().toDouble() / nums.size)
}

Leave a ReplyCancel reply