Immutable collections

I think that our junior developer learned their lesson. Instead, they produced this code, which is not very efficient, but which gets rid of those variables:

data class ScoreCollector(val scores: MutableList<Int> = mutableListOf())

val counter = ScoreCollector()

for (i in 1..1_000) {
counter.scores += Random().nextInt(100)

println(counter.scores.sumBy { it } / counter.scores.size)
}

But the maleficent thread strikes again:

thread(isDaemon= true, name="Maleficent") {
while(true) counter.scores.clear()
}

We again receive ArithmeticException.

It's not enough that your data class contains only values. If its value is a collection, it must be immutable in order for the data class to be considered immutable. The same rule is applied to classes contained within other data classes:

data class ImmutableScoreCollector(val scores: List<Int>)

Now the maleficent thread cannot even call clear() on this collection. But how should we add scores to it?

One option is to pass the entire list in the constructor:

val counter = ImmutableScoreCollector(List(1_000) {
Random().nextInt(100)
})

 

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.15.129.253