Which among importing companion object or extending trait is better

筅森魡賤 提交于 2019-12-01 23:43:32

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._

  ...
}

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.

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.

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