8

While experimenting with some stuff on the REPL, I got to a point where I needed something like this:

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

Just a simple class with an "==" operator.

Why doesn't it work???

Here's the result:

: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; } }
                                                                        ^

This is scala 2.8 RC1.

Thanks

4

2 回答 2

16

你必须定义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)...,然后它将具有一个访问器,您可以使用该访问器a.xequals运算符中访问。

于 2010-04-21T01:57:03.173 回答
7

由于与 Predef 中的某些代码重合,该错误消息有点令人困惑。但是这里真正发生的是你试图调用x你的A类上的方法,但没有定义具有该名称的方法。

尝试:

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

反而。此语法使 ,x的成员A与通常的访问器方法一起完成。

然而,正如 Ken Bloom 所提到的,重写equals而不是==.

于 2010-04-21T01:59:39.043 回答