This has been tested using scala 2.11.5. Consider the code below
class C(private val x: Int) { override def equals(obj: Any) = obj match { case other: C => x == other.x case _ => false } } println(new C(5) == new C(5))
it will compile and work like this java code (1.8)
class C { private int x; public C(int x) { this.x = x; } public boolean equals(Object obj) { if (obj instanceof C) { return ((C) obj).x == x; } else { return false; } } } System.out.println(new C(5).equals(new C(5)));
however, if you use the '[this]' modifier, the code below will not compile
class C(private[this] val x: Int) { override def equals(obj: Any) = obj match { case other: C => this.x == other.x
This is because in the first case, "x" is available at the class level, while in the second case it is a more strict instance level. This means that "x" can only be obtained from the instance to which it belongs. So, "this.x" is great, but "other.x" is not.
For more information on access modifiers, see Section 13.5, Scala Programming: A Comprehensive Walkthrough.
Marek Adamek Mar 11 '15 at 4:23 2015-03-11 04:23
source share