Reputation: 377
Excuse me, but I'm new to Scala. I have a abstract class and a concrete class that inherits from the abstract class and implements its fields.
abstract class Element {
var name: String
var description: String
}
class ConcreteElement (var name: String, var description: String)extends Element
Is this right? Yes? I have many classes that inherit from abstract class Element. Now I want to put a check on the variable name, that I want to instantiate name only in accordance with certain constraints. Where do I put this control? Obviously in abstract class Element.
In Scala A variable declaration var x: T is equivalent to declarations of a getter function x and a setter function x_=, defined as follows:
def x: T
def x_= (y: T): Unit
So I decided to declare the variables in this way and posizionere my constraints in the getter method name.
abstract class Element {
def name: String
def name_= (y: String): Unit = {CONSTRAINT}
var description: String
}
class ConcreteElement (var name: String, var description: String)extends Element
This reasoning is correct? ConcreteElement actually implements the fields of Element?
Upvotes: 1
Views: 436
Reputation: 3728
Your def name_=
works only if it has not been overriden by the sub-class. So I guess you need final
to prevent it being overriden.
abstract class Element {
protected var _name: String
final def name: String = _name
final def name_= (value: String) {
if (isBadValue(value)) throw new IllegalArgumentException
_name = value
}
var description: String
}
class ConcreteElement (protected var _name: String, var description: String) extends Element
Upvotes: 1