Scala 隐式类型转换和 ==

编程入门 行业动态 更新时间:2024-10-15 04:18:51
本文介绍了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 隐式类型转换和 ==

本文发布于:2023-07-14 10:11:03,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1104066.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:类型   隐式   Scala

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!