Self-titled field and accessor in Scala - 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.

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

Related

Use mocked function return value in real function call

Is it possible to use a mocked function inside a real function call? Both functions are in the same object. So for example, if I have
obj A {
def mockThis(value: Int): Int = {
value*5
}
def realFuncIWantToTest(value: Int): Int = {
val v = mockThis(value)
v
}
}
Obviously this is an extremely simple case and this isn't what my code is doing (v is actually a complicated object). Essentially I want realFuncIWantToTest to use the mocked function return value that I define.
Thanks!
You might be able to do this using Mockito's spies; see here for an example on that.
Spies basically work by having that spy wrapping around a real object of your class under test.
But one word here: even when it is possible, please consider changing your design instead. This "partial mocking" is often a good indication that your class is violating the single responsibility principle. Meaning: a class should be responsible for "one" thing. But the idea that you can / have to partially mock things within your class indicates that your class is responsible for at least two, somehow disconnect aspects.
In that sense: the better approach would be that mockThis() would be a call on another object; which could be inserted via dependency injection into this class.
Long story short: at least on a Java level your idea should work fine (where I have certain doubts that Mockito will work nicely with your scala objects) from a technical perspective; but from a conceptual point point; you should rather avoid doing it this way.

Scala code generation with annotations + macros or external script?

I want to know:
Can Scala annotations/transforms implement the code generation below? (objective)
What are the trade-offs as opposed to source code generation with an external tool? (objective)
Is there a better way / how would you do it? (subjective)
Background:
I'm designing an embedded database for Scala + Java as a side project. Although I want it to be usable from Java, I'm writing it in Scala for the extra flexibility/power and because writing Java code kills my soul.
I'm working out what I want model definitions to look like. My initial idea was to parse some model definition files and generate Scala classes. But I think now I'd like them to be definable in Scala code so that no parsing is required and people can bring the full power of Scala to bear in defining and customizing the models (e.g. custom column types.) That's a valuable feature from my Python/Django experience.
So far I have something like:
#model
class Person {
val Name = StringColumn(length=32)
val BirthDate = DateColumn(optional=true)
}
#model
class Student extends Person {
val GPA = FloatColumn(propertyName="gpa")
}
#model
class Teacher extends Person {
val salary = NumericColumn()
}
Which would generate:
class Person {
val Name = StringColumn(name="name", length=32)
val BirthDate = DateColumn(name="birthDate", optional=true)
// generated accessor methods
def name = Person.Name.get(...)
def name_= (name : String) : Unit = Person.Name.set(..., name)
// etc ...
}
// static access to model metadata, e.g. Person.Name is an immutable StringColumn instance
object Person extends Person
class Student extends Person {
val GPA = DoubleColumn(name = "GPA")
def gpa = ...
def gpa_= (value : Float) = ...
}
object Student extends Student
class Teacher extends Person {
// You get the idea
}
object Teacher extends Teacher
Looking at some examples online and doing some research, it seems like AST transforms using a special #model annotation could actually generate the needed code, maybe with a little bit of help, e.g. having the user define the object as well with the model definition. Am I right that this can be done?
Some problems that occur to me with this idea:
The object will be cluttered with properties that are not useful, all it needs are the Column objects. This could be fixed by splitting the class into two classes, PersonMeta and Person extends PersonMeta with Person object extending PersonMeta only.
IDEs will probably not pick up on the generated properties, causing them to underline them with wavy lines (eww...) and making it so auto-complete for property names won't work. The code would still be compile-time checked, so it's really just an IDE gotcha (Dynamic, no doubt, has the same problem.)
Code generation using a script is more IDE friendly, but it's hacky, probably more work, especially since you have to leave custom methods and things intact. It also requires a custom build step that you have to run whenever you change a model (which means you can forget to do it.) While the IDE might not help you with macro code generation (yet, anyway) the compiler will shout at you if you get things wrong. That makes me lean towards doing it with macros + annotation.
What do you think? I'm new to Scala, I kind of doubt I've hit on the best way to define models and generate implementations for them. How would you do it better?
It's possible yeah. Macros can be unpleasant to write and debug, but they do work.
Seems like you already have your solution there
Scala IDEs tend to handle macros correctly-ish (I mean, they have to, they're part of the language and used in some pretty fundamental libraries), so I wouldn't worry about that; if anything a macro is more ide-friendly than an external codegen step because a macro will stay in sync with a user's changes.
I'd see whether you can achieve what you want in vanilla scala before resorting to a macro. Remember that your class-like things don't necessarily have to be actual case classes; take a look at Shapeless generic records for an idea of how you can represent a well-typed "row" of named values from somewhere external. I think a system that could map a structure like those records to and from SQL might end up being more principled (that is, easier to reason about) than one based on "special" case classes.

Recognize setter invocations

I have an application where some var values ought to be published to a message queue on change. That is, if a var's setter is invoked I want this to be noticed somehow and after setting the new value I want it to be published to the MQ.
I did something like this some time ago with Perl/Moose by setting an after-modifier (doing the publishing) on methods with a certain method attribute. That solution was very elegant and required no syntactical overhead besides the additional method attribute.
What would be a good solution using Scala's (2.10) capabilities without using clumsy OO patterns?
Update: What I would like to achieve is that the code looks something like this:
#Publishable var someProperty = 42
or
domainSpecificLanguageMagic someProperty = 42
One of the challenges is that these properties might be reflectively set, so a setter-method with a different name is (probably?) not an option.
I guess the way to go is scala virtualized: it has some built in primitives that allow you to change language semantic including assignment one. It isn't stock scala , but it is quite officially supported and new release usually comes no too late after the ordinary one (in a matter of weeks). (I'm confused it with another scala framework -- LMS, AFAIS it isn't supported quite good ATM, but still should solve your problem)
You can make the property private (and give it a variant name) and define its accessor and mutator methods:
class C1(...) {
private var iProp: Int = 0
def prop: Int = iProp
/* Put additional logic associated with mutation here: */
def prop_=(newProp: Int): Unit = iProp = newProp
}

Scala: Do classes that extend a trait always take the traits properties?

Given the following:
class TestClass extends TestTrait {
def doesSomething() = methodValue + intValue
}
trait TestTrait {
val intValue = 4
val unusedValue = 5
def methodValue = "method"
def unusedMethod = "unused method"
}
When the above code runs, will TestClass actually have memory allocated to unusedValue or unusedMethod? I've used javap and I know that there exists an unusedValue and an unusedMethod, but I cannot determine if they are actually populated with any sort of state or memory allocation.
Basically, I'm trying to understand if a class ALWAYS gets all that a trait provides, or if the compiler is smart enough to only provide what the class actually uses from the trait?
If a trait always imposes itself on a class, it seems like it could be inefficient, since I expect many programmers will use traits as mixins and therefore wasting memory everywhere.
Thanks to all who read and help me get to the bottom of this!
Generally speaking, in languages like Scala and Java and C++, each class has a table of pointers to its instance methods. If your question is whether the Scala compiler will allocate slots in the method table for unusedMethod then I would say yes it should.
I think your question is whether the Scala compiler will look at the body of TestClass and say "whoa, I only see uses of methodValue and intValue, so being a good compiler I'm going to refrain from allocating space in TestClass's method table for unusedMethod. But it can't really do this in general. The reason is, TestClass will be compiled into a class file TestClass.class and this class may be used in a library by programmers that you don't even know.
And what will they want to do with your class? This:
var x = new TestClass();
print(x.unusedMethod)
See, the thing is the compiler can't predict who is going to use this class in the future, so it puts all methods into its method table, even the ones not called by other methods in the class. This applies to methods declared in the class or picked up via an implemented trait.
If you expect the compiler to do global system-wide static analysis and optimization over a fixed, closed system then I suppose in theory it could whittle away such things, but I suspect that would be a very expensive optimization and not really worth it. If you need this kind of memory savings you would be better off writing smaller traits on your own. :)
It may be easiest to think about how Scala implements traits at the JVM level:
An interface is generated with the same name as the trait, containing all the trait's method signatures
If the trait contains only abstract methods, then nothing more is needed
If the trait contains any concrete methods, then the definition of these will be copied into any class that mixes in the trait
Any vals/vars will also get copied verbatim
It's also worth noting how a hypothetical var bippy: Int is implemented in equivalent java:
private int bippy; //backing field
public int bippy() { return this.bippy; } //getter
public void bippy_$eq(int x) { this.bippy = x; } //setter
For a val, the backing field is final and no setter is generated
When mixing-in a trait, the compiler doesn't analyse usage. For one thing, this would break the contract made by the interface. It would also take an unacceptably long time to perform such an analysis. This means that you will always inherit the cost of the backing fields from any vals/vars that get mixed in.
As you already hinted, if this is a problem then the solution is just use defs in your traits.
There are several other benefits to such an approach and, thanks to the uniform access principle, you can always override such a method with a val further down in the inheritance hierarchy if you need to.

Scala - are classes sufficient?

Coming from Java I am confused by the class/object distinction of scala.
Note that I do not ask for the formal difference; there are enough
references on the web which explain this, and there are related questions on
SO.
My questions are:
Why did the designers of scala
choosed to make things more
complicated (compared to Java or
C#)? What disadvantages do I have to
expect if I ignore this distinction
and declare only classes?
Thanks.
Java classes contain two completely different types of members -- instance members (such as BigDecimal.plus) and static members (such as BigDecimal.valueOf). In Scala, there are only instance members. This is actually a simplification! But it leaves a problem: where do we put methods like valueOf? That's where objects are useful.
class BigDecimal(value: String) {
def plus(that: BigDecimal): BigDecimal = // ...
}
object BigDecimal {
def valueOf(i: Int): BigDecimal = // ...
}
You can view this as the declaration of anonymous class and a single instantiation thereof:
class BigDecimal$object {
def valueOf(i: Int): BigDecimal = // ...
}
lazy val BigDecimal = new BigDecimal$object
When reading Scala code, it is crucial to distinguish types from values. I've configured IntelliJ to hightlight types blue.
val ls = List.empty[Int] // List is a value, a reference the the object List
ls: List[Int] // List is a type, a reference to class List
Java also has another degree of complexity that was removed in Scala -- the distinction between fields and methods. Fields aren't allowed on interfaces, except if they are static and final; methods can be overriden, fields instead are hidden if redefined in a subclass. Scala does away with this complexity, and only exposes methods to the programmer.
Finally, a glib answer to your second question: If you don't declare any objects, you're program may never run, as you to define the equivalent of public static void main(String... args) {} in Scala, you need at least one object!
Scala doesn't have any notion of static methods with standard classes, so in those scenarios you'll have to use objects. Interesting article here which provides a good intro:
http://www.codecommit.com/blog/scala/scala-for-java-refugees-part-3
(scroll down to Scala’s Sort-of Statics)
One way to look at it is this. An executing program consists of a community of objects and threads. Threads execute code within the context of objects -- i.e. there is always a "this" object that a thread is executing within. This is a simplification from Java in the sense that in Java, there is not always a "this". But now there is a chicken/egg problem. If objects are created by threads and threads are executed within objects, what object is the first thread initially executing within. There has to be a nonempty set of objects that exist at the start of program execution. These are the objects declared with the object keyword.