Why does set.average return a different value than array.average?

Viewed 33

I was tinkering around with my IDE and I stumbled across something interesting. Check out this code:

val arr1 = intArrayOf(3, 3, 2)
val set1 = setOf(3, 3, 2)

println(arr1.average())
println(set1.average())

These appear pretty similar, but it returns this:

2.6666666666666665
2.5

Why are these returning different values?

1 Answers

From kotlinlang.org:

[A set is] A generic unordered collection of elements that does not support duplicate elements.

This means that even though you're initializing a set as {3, 3, 2}, it's actually {3, 2}. The average of {3, 2} is 2.5.

Related