Scala 隐式类型转换和 == [英] Scala implicit type conversion and ==

查看:47
本文介绍了Scala 隐式类型转换和 ==的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能告诉我为什么隐式类型转换不适用于 ==?

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 隐式类型转换和 ==的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆