In Scala, it’s possible to define class attributes in the constructor. But once you declare them there, it’s not possible anymore to change the behavior (getters and setters), like you can when declaring in the class body?
Example:
class MyExample(var attribute : String)
{
def attribute() //trying to override getter <- doesn't work
}
class MyExample(theAttribute : String)
{
def attribute = theAttribute //overriding default accessor (was var)
}
If it’s not possible, why is it so? It seems confusing when you show people that they can easily create attributes by setting var or val in constructor, and not care about getters and setters (they can change if they need), to ultimately find that, in fact, you should avoid using those kind of facilitations.
Let’s for a moment imagine that it was possible to override the generated accessor-method:
Without a further qualification it is impossible to tell whether the name
attributewithin method body refers to the class field or recursively to the method itself.By design in Scala methods and fields belong to the same namespace, this, known as Uniform Access Principle, gives the ability to change an internal implementation without breaking the external interface.
An initial implementation could be:
Then changed onto:
And then
Or
All without breaking any of the dependent code.
When field is defined as part of a constructor the automatically generated accessor-methods are syntactic sugar. The sugar eases quick prototyping and helps to keep the code concise. Nonetheless, whenever you want to add more substance you must use the full syntax.