Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange behaviour of the Array type with `==` operator

scala> List(1,2,3) == List(1,2,3)

res2: Boolean = true

scala> Map(1 -> "Olle") == Map(1 -> "Olle")

res3: Boolean = true

But when trying to do the same with Array, it does not work the same. Why?

scala> Array('a','b') == Array('a','b')

res4: Boolean = false

I have used 2.8.0.RC7 and 2.8.0.Beta1-prerelease.

like image 577
olle kullberg Avatar asked Jul 09 '10 14:07

olle kullberg


1 Answers

The root cause the it is that fact that Scala use the same Array implementation as Java, and that's the only collection that not support == as equality operator.

Also, it's important to note that the chosen answer suggest equally sameElements and deep comparison when actually it's preferred to use:

Array('a','b').deep.equals(Array('a','b').deep)

Or, because now we can use == back again:

Array('a','b').deep == Array('a','b').deep

Instead of:

Array('a','b').sameElements(Array('a','b'))

Because sameElements won't for for nested array, it's not recursive. And deep comparison will.

like image 143
Johnny Avatar answered Nov 16 '22 00:11

Johnny