问题
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