Which among importing companion object or extending trait is better

前端 未结 3 1598
名媛妹妹
名媛妹妹 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._
    
      ...
    }
    

提交回复
热议问题