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
You have to define the
equals(other:Any):Booleanfunction, then Scala gives you==for free, defined asSee chapter 28 (Object Equality) of Programming in Scala for more on how to write the
equalsfunction so that it’s really an equivalence relation.Moreover, the parameter
xthat you pass to your class isn’t stored as a field. You need to change it toclass A(val x:Int)…, and then it will have an accessor that you can use to accessa.xin theequalsoperator.