首页 文章

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

提问于
浏览
8

在试验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 .

谢谢

2 回答

  • 7

    你必须定义 equals(other:Any):Boolean 函数,然后Scala免费为你提供 == ,定义为

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

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

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

  • 15

    由于与Predef中的某些代码重合,错误消息有点令人困惑 . 但's really going on here is that you'试图在 A 类上调用 x 方法,但没有定义具有该名称的方法 .

    尝试:

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

    代替 . 此语法使 x 成为 A 的成员,并使用通常的访问器方法 .

    然而,正如Ken Bloom所提到的,覆盖 equals 而不是 == 是个好主意 .

相关问题