It was empirically discovered that Scala allows name clashes for object-private variables and methods like below:
class Test {
private[this] var x = 1
def x(): String = this.x.toString
}
This code is valid at least for Scala 2.10 and produces exactly what I expect (decompiled into Java):
public class Test {
private int x;
public String x() {
return BoxesRunTime.boxToInteger(x).toString();
}
public Test() {
x = 1;
}
}
The problem is that I'm not sure if I can rely on this behavior in later Scala releases because I was not able to find an authoritative proof in the specifications that this behavior is by design. So, can anybody suggest me such a source of knowledge?
Update: My goal is to use this approach to map Hibernate data model with Scala classes. Since there is no easy way to enable Hibernate to support Scala collections, I wanted to map a Java collection in a private field which is then wrapped into a Scala collection in a self-titled accessor method. The key requirement is to keep the field and the method with the same name because I want also to preserve the logical Hibernate collection name, e.g. to reference it in HQL.
these collisions are totally normal. But keep in mind that reading your code might become a problem, since these collisions should appear (if you need that) only for getters/setters. In other case please use clear method names like:
def xAsString():
This thread can also be helpful scala discussion on name collisions
and this naming conventions by Daniel Spewaks
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With