Give me some help, I just cannot solve this problem.
How do I ensure that constraints on getter methods are always respected?
My classes have this form:
abstract class Element {
var name: String
var description: String
}
class Component (var name: String, var description: String) extends Element
For the purpose of my project I need to use var.
I want to put constraints on the field name that must always be respected.
Both when I create an instance of Component as follows:
val C1 = new Component ("C1 Component", "Description of C1")
Both when I change the value:
C1.name = "new value"
If I create the classes in this way:
abstract class Element {
protected var _name : String
// Getter
final def name = _name
// Setter
final def name_= (value:String):Unit =
if (value.size < 5) println ("ERROR: Bad Value")
else _name = value
var description: String
}
class Component (protected var _name : String, var description: String) extends Element
In the main method, because I do not have control here:
val C1 = new Component ("C1", "Description of C1")
But only later, when I change the value:
C1.name = "comp"
I want my getter to always be respected.
How do I do this?
Also, make
var _nameprivate, so subclasses can’t set it without using the setter.