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:

  1. (best in circumstances) use composition instead of inheritance. instead of class employee(...) extends person(...)) have class employee(person: person, company: string).

  2. if have fixed hierarchy of subclasses, then, mention in comment, dispatch on type in implicitpersonwrites. isn't particularly ugly; happens option, list, etc. time. ideally can turn person algebraic data type.

  3. 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:

    1. person , subclasses have know jsvalues;

    2. this can done cases writes type argument used argument.


Comments

Popular posts from this blog

java - Date formats difference between yyyy-MM-dd'T'HH:mm:ss and yyyy-MM-dd'T'HH:mm:ssXXX -

c# - Get rid of xmlns attribute when adding node to existing xml -