Scala: force method calls in class hierarchy

和自甴很熟 提交于 2020-01-06 05:49:28

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!