scala - Implicit writes for child class type -
i have class person , class employee. class employee extends class person.
my current implicit writes convert classes json looks this:
implicit val implicitpersonwrites = new writes[person] { def writes(v: person): jsvalue = { json.obj("label" -> v.label, "age" -> v.age) } } implicit val implicitemployeewrites = new writes[employee] { def writes(v: employee): jsvalue = { json.obj("label" -> v.label, "age" -> v.age, "company" -> v.company) } } the problem object of type employee, implicit write person superclass used. @ end fields specific employee class not present in output. how make implicit writes in case of inheritance?
three options:
(best in circumstances) use composition instead of inheritance. instead of
class employee(...) extends person(...))haveclass employee(person: person, company: string).if have fixed hierarchy of subclasses, then, mention in comment, dispatch on type in
implicitpersonwrites. isn't particularly ugly; happensoption,list, etc. time. ideally can turnpersonalgebraic data type.use inheritance have:
implicit val implicitpersonwrites = new writes[person] { def writes(v: person): jsvalue = v.tojsvalue } // no implicitemployeewrites class person(...) { def tojsvalue = json.obj("label" -> label, "age" -> age) } class employee(...) extends person(...) { override def tojsvalue = json.obj("label" -> label, "age" -> age, "company" -> company) }this has obvious drawbacks:
person, subclasses have knowjsvalues;this can done cases
writestype argument used argument.
Comments
Post a Comment