Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Handling division by zero exception in average calculation for empty lists

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading