Which among importing companion object or extending trait is better

前端 未结 3 1491
名媛妹妹
名媛妹妹 2021-01-23 05:36

I have a JSON protocol written in spray

trait MyJsonProtocol {
   //some logic
}

object MyJsonProtocol extends MyJsonProtocol {

}

Now which i

相关标签:
3条回答
  • 2021-01-23 05:48

    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._
    
      ...
    }
    
    0 讨论(0)
  • 2021-01-23 05:48

    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.

    0 讨论(0)
  • 2021-01-23 05:52

    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.

    0 讨论(0)
提交回复
热议问题