加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

简单的Scala语法 – 尝试定义“==”运算符 – 我缺少什么?

发布时间:2020-12-16 09:09:34 所属栏目:安全 来源:网络整理
导读:在试验REPL上的一些东西时,我得到了一个我需要这样的东西: scala class A(x:Int) { println(x); def ==(a:A) : Boolean = { this.x == a.x; } } 只是一个带有“==”运算符的简单类. 为什么不工作? 这是结果: :10: error: type mismatch; found : A requir
在试验REPL上的一些东西时,我得到了一个我需要这样的东西:

scala> class A(x:Int) { println(x); def ==(a:A) : Boolean = { this.x == a.x; } }

只是一个带有“==”运算符的简单类.

为什么不工作?

这是结果:

:10: error: type mismatch;
 found   : A
 required: ?{val x: ?}
Note that implicit conversions are not applicable because they are ambiguous:
 both method any2ArrowAssoc in object Predef of type [A](x: A)ArrowAssoc[A]
 and method any2Ensuring in object Predef of type [A](x: A)Ensuring[A]
 are possible conversion functions from A to ?{val x: ?}
       class A(x:Int) { println(x); def ==(a:A) : Boolean = { this.x == a.x; } }
                                                                        ^

这是scala 2.8 RC1.

谢谢

解决方法

你必须定义equals(其他:Any):布尔函数,然后Scala给你==免费,定义为

class Any{
  final def == (that:Any):Boolean =
    if (null eq this) {null eq that} else {this equals that}
}

有关如何编写equals函数以使其真正成为等价关系的更多信息,请参阅Scala中编程的第28章(对象等式).

此外,传递给类的参数x不会存储为字段.您需要将其更改为类A(val x:Int)…,然后它将具有一个可用于访问equals运算符中的a.x的访问器.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读