DEV Community


Discussion on: Look ma', without loops!

moopet profile image
Ben Sinclair

What happens when there are no students in the class that term?

chrisvasqm profile image
Christian Vasquez Author

As it is right now, when the calculateAverageScore() function gets executed, since the students.size is zero, it will cause a java.lang.ArithmeticException: / by zero 💥

neonailol profile image
Valeriy Zhirnov • Edited

To avoid this you can use average function from stdlib, so istead of this:

fun calculateAverageScore(students: Array<Student>) = 
        students.sumBy { it.score } / students.size

You can write:

fun calculateAverageScore(students: Array<Student>) = { it.score }.average()
Forem Open with the Forem app