Why does `Array(0,1,2) == Array(0,1,2)` not return the expected result?

梦想的初衷 提交于 2019-12-17 07:24:40

问题


As far as I understand, Scala's == defines the natural equality of two objects.

I expected that Array(0,1,2) == Array(0,1,2) compares the natural equality. For example, checks if all elements of the array return true when compared with the corresponding elements of the other array.

People told me that Scala's Array is just a Java [] which only compares identity. Wouldn't it be more meaningful to override Array'sequals method to compare natural equality instead?


回答1:


Scala 2.7 tried to add functionality to Java [] arrays, and ran into corner cases that were problematic. Scala 2.8 has declared that Array[T] is T[], but it provides wrappers and equivalents.

Try the following in 2.8 (edit/note: as of RC3, GenericArray is ArraySeq--thanks to retronym for pointing this out):

import scala.collection.mutable.{GenericArray=>GArray, WrappedArray=>WArray}
scala> GArray(0,1,2) == GArray(0,1,2)
res0: Boolean = true

scala> (Array(0,1,2):WArray[Int]) == (Array(0,1,2):WArray[Int])
res1: Boolean = true

GenericArray acts just like Array, except with all the Scala collections goodies added in. WrappedArray wraps Java [] array; above, I've cast a plain array to it (easier than calling the implicit conversion function) and then compared the wrapped arrays. These wrappers, though backed by a [] array, also give you all the collection goodies.




回答2:


Scala doesn't override Array's equality because it's not possible. One can only override methods when subclassing. Since Array isn't being subclassed (which isn't possible), Scala cannot override its methods.




回答3:


But Scala's String is also just a Java String but Scala overrides equals to compare natural equality.

Scala doesn't override anything there; java.lang.String has a value-dependant implementation of equals() (like many other Java classes, but unlike arrays).



来源:https://stackoverflow.com/questions/2481149/why-does-array0-1-2-array0-1-2-not-return-the-expected-result

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