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

人走茶凉 提交于 2019-11-28 09:17:17

Because the definition of "equals" for Arrays is that they refer to the same array.

This is consistent with Java's array equality, using Object.Equals, so it compares references.

If you want to check pairwise elements, then use sameElements

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

or deepEquals, which has been deprecated in 2.8, so instead use:

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

There's a good Nabble discussion on array equality.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!