In Maronic, we would like to count the average score over one thousand games. For that, we have the following data class:
data class AverageScore(var totalScore: Int = 0,
var gamesPlayed: Int = 0) {
val average: Int
get() = if (gamesPlayed <= 0)
0
else
totalScore / gamesPlayed
}
We were smart: we protected ourselves from any invalid output by checking for divisions by zero.
But what will happen when we write the following code?
val counter = AverageScore()
thread(isDaemon = true) {
while(true) counter.gamesPlayed = 0
}
for (i in 1..1_000) {
counter.totalScore += Random().nextInt(100)
counter.gamesPlayed++
println(counter.average)
}
Soon enough, you'll receive ArithmeticException anyway. Our counter somehow becomes zero.
If you want your data classes to be immutable, be sure to specify all their properties as val (values), and not var (variables).