Just like the question. Does scala promote it same way as Java? Or has it been evolved to be more idiomatic to Scala? Or has it been made irrelevant?
POJOs and JavaBeans meaning:
- Constructor that takes no parameters
- attributes are private, getters and setters are public
- getters and setters defines properties, hiding attributes
Also, does Scala have opinions (sorry, I dislike using this term) on using the old public
, private
, protected
attribute designs that is relevant to this question?
Scala also has POJO-like idioms but they are different than JavaBeans and Scala puts emphasis on different aspects.
Scala has different naming conventions:
This way you can always write
obj.foo
andobj.foo = bar
even if you decide to switch from getters/setters to direct field access and vice-versa. This is called uniform access principle.Due to Java interoperability,
@BeanProperty
annotation was introduced:the code above not only creates Scala-like getters/setters, but Java-like as well, so all Java frameworks work seamlessly.
Scala forces you to decide between variables (
var
) and values (val
), so you find yourself much more often using immutable objectsI really prefer immutable objects and initialization in constructor, which has been made very easy in Scala:
or even (
val
by default incase
classes):This piece of code is brilliant in its simplicity. However, if you need to cooperate with Java frameworks, you still need no-argu constructor and setters:
Note
val
being replaced byvar
.Access modifiers in Scala have slightly better defaults compared to Java:
Variables
a
andb
will becomeprivate
fields withpublic
getters/setters (fields are private by default, methods are public).c
andd
are private variables as well. But the extraprivate[this]
makesd
be accessible directly internally in the class rather than by private getter/setter.Because
x
is used somewhere beside the constructor, Scala automatically creates private field for it as well. However no getters/setters are generated, it is accessed directly intwisted
method (same asd
).UPDATE: In comments you are asking about renaming getters/setters. Here is even more complex example. Getters/setters are computing the value based on two fields at the same time:
Looks complicated inside, but from the outside it looks like good old property:
Just like if it was: