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

Ale*_*x R 8 scala scala-2.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.

谢谢

Ken*_*oom 16

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

class Any{
  final def == (that:Any):Boolean =
    if (null eq this) {null eq that} else {this equals that}
}
Run Code Online (Sandbox Code Playgroud)

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

此外,x传递给类的参数不会存储为字段.您需要将其更改为class A(val x:Int)...,然后它将具有可用于a.xequals操作员中访问的访问者.

  • 我认为它更准确地说它不是*可访问*作为一个字段,即它不会生成访问器方法,除非你在传入它时将其声明为`val`. (2认同)

Dav*_*low 7

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

尝试:

class A(val x: Int) { println(x); def ==(a: A): Boolean = { this.x == a.x } }
Run Code Online (Sandbox Code Playgroud)

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

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