导入伴侣对象或扩展特性中哪个更好 [英] Which among importing companion object or extending trait is better

查看:69
本文介绍了导入伴侣对象或扩展特性中哪个更好的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用Spray编写的JSON协议

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 ?

推荐答案

如果要创建用于喷雾的JsonFormat实例,则可以直接创建objectimport进行创建.这意味着您只有一个隐式val和对象的实例.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆