没有返回预期的结果

没有返回预期的结果

本文介绍了为什么`Array(0,1,2) == Array(0,1,2)` 没有返回预期的结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知,Scala 的 == 定义了两个对象的自然相等性.

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

我期望 Array(0,1,2) == Array(0,1,2) 比较自然相等.例如,检查数组的所有元素在与另一个数组的相应元素进行比较时是否都返回 true.

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.

人们告诉我 Scala 的 Array 只是一个 Java [],它只比较身份.重写Arrayequals方法来比较自然相等不是更有意义吗?

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?

推荐答案

Scala 2.7 尝试向 Java [] 数组添加功能,但遇到了有问题的极端情况.Scala 2.8 已经声明 Array[T]T[],但它提供了包装器和等价物.

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.

在 2.8 中尝试以下内容(编辑/注意:从 RC3 开始,GenericArrayArraySeq——感谢retronym 指出这一点):

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 就像 Array 一样,除了添加了所有 Scala 集合的好东西. WrappedArray 包装 Java []数组;上面,我已经向它投射了一个普通数组(比调用隐式转换函数更容易),然后比较了包装的数组.这些包装器虽然由 [] 数组支持,但也为您提供了所有集合的好东西.

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.

这篇关于为什么`Array(0,1,2) == Array(0,1,2)` 没有返回预期的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 04:52