问题
I have a hierarchy of ConfigBuilder classes which have the role of creating Config instances. My superclass is an AbstractConfigBuilder which has a method build. I want that build always calls a method validate before actually building the object. So, in the abstract super class I have
val commonField: String //one of many fields common to all the hierarchy
abstract def build: Config //building logic left to the subclasses
def validate: Boolean = {
// here some common checks
commonField.size > 0
}
In the subclass
val subFiled: String
def build: Config = {
if(validate) // call to validation
new ConfigImplementation(commonField, subfield)
else throw new Error()
}
def validate: Boolean = {
super.validate
subField.size > 0
}
What I would like to achieve is to avoid call to validation in every subclass of the superclass. My behaviour is clear and fixed: build a config, only after validating its parameters (some common ones in the superclass, the rest in the subclass). Could you suggest me the best way to do this?
回答1:
Just split your build into two:
protected abstract def buildInternal: Config
def validate: Boolean
final def build: Config = if(validate) buildInternal else throw new Error()
来源:https://stackoverflow.com/questions/51603138/scala-force-method-calls-in-class-hierarchy