What def, val, and var fields in Scala traits look like after they’re compiled (including the classes that extend them)
I generally have a pretty good feel for how Scala traits work, and how they can be used for different needs. As one example, a few years ago I learned that it’s best to define abstract fields in traits using
def. But there are still a few things I wonder about.
Today I had a few free moments and I decided to look at what happens under the covers when you use
var fields in traits, and then mix-in or extend those traits with classes. So I created some examples, compiled them with
scalac -Xprint:all, and then decompiled them with JAD to see what everything looks like under the covers.
I was initially going to write a summary here, but if you want to know how things work under the hood, I think it helps to work through the examples, so for today I’ll leave that as an exercise for the reader.
If you want to automatically generate getters and setters for your Java JavaBean classes, Project Lombok has some annotations that you can use.
This is an excerpt from the Scala Cookbook (partially modified for the internet). This is Recipe 17.6, “How to create JavaBeans in Scala (to interact with Java libraries).”
You need to interact with a Java class or library that accepts only classes that conform to the JavaBean specification.
@BeanProperty annotation on your fields, also making sure you declare each field as a
@BeanProperty annotation can be used on fields in a Scala class constructor:
This is an excerpt from the Scala Cookbook (partially modified for the internet). This is Recipe 5.6, “How to force calling methods to leave parentheses off accessor (getter) methods.”
You want to enforce a coding style where getter/accessor methods can’t have parentheses when they are invoked.
Define your getter/accessor method without parentheses after the method name:
This is an excerpt from the Scala Cookbook (partially modified for the internet). This is Recipe 4.14, “How to generate boilerplate code with Scala case classes.”
This is an excerpt from the Scala Cookbook (partially modified for the internet). This is Recipe 4.7, “How to prevent getter and setter methods from being generated in Scala classes.”
When you define a class field as a
var, Scala automatically generates getter and setter methods for the field, and defining a field as a
val automatically generates a getter method, but you don’t want either a getter or setter.
This is an excerpt from the Scala Cookbook (partially modified for the internet). This is Recipe 4.6, “How to override default accessors and mutators in Scala classes.”
You want to override the getter or setter methods that Scala generates for you.
I just ran into one thing I wish I had included in the Scala Cookbook that I didn’t include: How to access a
var field in a Scala object from your Java code.
In short, if you have a field named
appName defined in a Scala object, like this: