Tro*_*lum 8 scala type-conversion
任何人都可以告诉我为什么隐式类型转换不起作用==
?
例:
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)
}
Run Code Online (Sandbox Code Playgroud)
现在我能做到:
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
Run Code Online (Sandbox Code Playgroud)
但:
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
Run Code Online (Sandbox Code Playgroud)
Dan*_*ral 14
您缺少Scala的一个基本方面,即平等的工作方式.
基本上,所有类扩展都AnyRef
实现以下方法:
def equals (arg0: Any) : Boolean
Run Code Online (Sandbox Code Playgroud)
并且所有类都实现以下方法:
def == (arg0: Any) : Boolean
Run Code Online (Sandbox Code Playgroud)
现在,你应该覆盖不==
,但是equals
.该方法==
将调用equals
,但Java代码将使用equals
,而不是==
.这不是你看到的问题的原因,但重要的是我认为值得一提.
现在,关于隐式不工作,请记住只有在没有方法满足您的代码时才会查找implicits.然而,Int
的==
可相比BitArray
,作为==
接收类型的参数Any
.因此,Int
调用了等式方法,并且没有查找隐式方法.
要覆盖==
运算符,您应该实际覆盖该equals
方法:
override def equals(other: Any): Boolean = other match {
case ba: BitArray => value == ba.value
case _ => false
}
Run Code Online (Sandbox Code Playgroud)
你不能使你的实例BitArray
等于a Long
并仍然遵守平等契约(即它不会是对称的).
归档时间: |
|
查看次数: |
2538 次 |
最近记录: |