DEV Community

Discussion on: Look ma', without loops!

Collapse
 
chrisvasqm profile image
Christian Vasquez

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 💥

Collapse
 
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>) = 
        students.map { it.score }.average()