Self-titled field and accessor in Scala

It has been empirically discovered that Scala resolves name collisions for object-private variables and methods, as shown 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 in 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 versions of Scala, because I could not find authoritative evidence in the specifications that this behavior is by design. So, can anyone suggest me such a source of knowledge?

Update. My goal is to use this approach to map a Hibernate data model to Scala classes. Since there is no easy way to enable Hibernate to support Scala collections, I wanted to display the Java collection in a private field, which is then wrapped in a Scala collection in a single-user access method. The main requirement is to save the field and method with the same name, because I want to also save the logical name of the Hibernate collection, for example. reference it in HQL.

+6
source share
1 answer

these collisions are completely normal. But keep in mind that reading code can be a problem, as these collisions should appear (if you need it) only for getters / setters. In other cases, use the following method names:

 def xAsString(): 

This thread can also be a useful scala discussion of name conflicts.

and these are the Daniel Spvaks naming conventions

+3
source

Source: https://habr.com/ru/post/947823/


All Articles