Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Self-titled field and accessor in Scala

Tags:

scala

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.

like image 654
Jiří Vypědřík Avatar asked Jun 21 '13 10:06

Jiří Vypědřík


1 Answers

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

like image 61
Tala Avatar answered Oct 09 '22 23:10

Tala