Which among importing companion object or extending trait is better

江枫思渺然 提交于 2019-12-02 02:48:46

问题


I have a JSON protocol written in spray

trait MyJsonProtocol {
   //some logic
}

object MyJsonProtocol extends MyJsonProtocol {

}

Now which is better ?? Importing this companion object or extending the trait ?


回答1:


If you are creating some JsonFormat instances for spray, then you can just create an object directly and import that. This means that you only have a single instance of your implicit vals and objects.

object MyJsonProtocol extends DefaultJsonProtocol {
  implicit object MyTypeJsonFormat extends RootJsonFormat[MyType] {
    def write(v: MyType): JsValue = ...
    def read(value: JsValue): MyType = ...
  }

  implicit val myClassFormat = jsonFormat5(MyClass)
}

class OtherClass {
  import MyJsonProtocol._

  ...
}



回答2:


It depends on the scenario, Because a companion class or object can access the private members of its companion. Use a companion object for methods and values which are not specific to instances of the companion class. If you just want multiple inheritance but allow code reusability then trait is fine.

Hope it helps.




回答3:


This depends on your logic. If you define some implicits, importing an object and extending a trait are different. If you import you define implicits of the same priority as local ones. If you extend you create low-priority implicits in comparison with local ones.



来源:https://stackoverflow.com/questions/55107847/which-among-importing-companion-object-or-extending-trait-is-better

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