谁能告诉我为什么隐式类型转换不适用于 ==?
Can anyone enlighten me as to why implicit type conversion does not work with ==?
示例:
class BitArray(l: Int, v: Long) { val length = l var value = v def ==(that: BitArray) = value == that.value def ==(integer: Long) = value == integer def +(that: BitArray) = new BitArray(length,value+that.value ) def +(integer: Long) = new BitArray(length,value+integer ) //... } object BitArray{ implicit def longToBitArray(x : Long) = new BitArray(64,x) def apply(v: Long) :BitArray = apply(64,v) }现在我可以:
scala> BitArray(5) + 5 res13: BitArray = 00000000000000000000000000001010 scala> 5 + BitArray(5) res14: BitArray = 00000000000000000000000000001010 scala> BitArray(5) == 5 res15: Boolean = true scala> BitArray(5) == 6 res16: Boolean = false但是:
scala> 5 == BitArray(5) <console>:11: warning: comparing values of types Int and BitArray using `==' will always yield false 5 == BitArray(5) ^ res17: Boolean = false 推荐答案您缺少 Scala 的一个基本方面,这就是平等的工作原理.
You are missing a fundamental aspect of Scala, which is how equality works.
基本上,所有扩展 AnyRef 的类都实现以下方法:
Basically, all classes extending AnyRef implement the following method:
def equals (arg0: Any) : Boolean并且所有类都实现了以下方法:
And all classes implement the following method:
def == (arg0: Any) : Boolean现在,您应该覆盖的不是==,而是equals.方法== 将调用equals,但Java 代码将使用equals,而不是==.这不是你看到的问题的原因,但它足够重要,我认为值得一提.
Now, you should override not ==, but equals. The method == will call equals, but Java code will use equals, not ==. This is not the cause of the problem you see, but it is important enough that I think it is worth mentioning.
现在,至于隐式不起作用,请记住只有在没有满足您的代码的方法时才会查找隐式.但是,Int 的 == 可以与 BitArray 进行比较,因为 == 接收类型为 任何.因此,调用了Int的相等方法,并没有寻找隐式.
Now, as to the implicit not working, remember that implicits are only looked for if there is no method that satisfy your code. However, Int's == can be compared with BitArray, as == receives an argument of type Any. Therefore, Int's equality method is called, and no implicit is looked for.
更多推荐
Scala 隐式类型转换和 ==
发布评论