Scala: Copying a generic case class into another -


i have following setup, want copy instance of basedata of moredata:

sealed trait basedata {   def weight: int   def priority: int }   sealed trait moredata {   def weight: int   def priority: int   def t: string   def id: string }   case class data1(override val weight: int, override val priority: int) extends basedata  case class moredata1 (override val weight:int, override val priority: int, override val t: string, override val id: string)extends moredata 

so copying mydata otherdata below:

val mydata = data1(1,1)  val otherdata = moredata1 (2,2,"c","abcd")  

would yield: moredata1(1,1,"c","abcd").

to this, want use function following signature, because have more 1 case class extending both basedata , moredata:

def copyover[a <:basedata, b <:moredata](from: a, to: b) = {}  

i'm sure can shapeless, haven't figured out how. there examples (here) on copying case classes extending same trait, , others (here) mapping values between different case classes via generic representation. haven't figured out how use labelledgeneric trait-bounded arguments passed copyover. don't want have hardcode fields in otherdata aren't present in mydata.

i'm looking generic implementation. ideas?

you should able use updaterepr type class your first shapeless example.

you define copyover using updaterepr follows :

import shapeless._  // basedata, moredata, data1, moredata1 // updaterepr ...  def copyover[a <: basedata, b <: moredata, r <: hlist](   from: a,   to: b )(implicit    lgen: labelledgeneric.aux[a, r],   update: updaterepr[b, r] ): b = update(to, lgen.to(from)) 

which use follows :

val mydata = data1(1,1)  val otherdata = moredata1(2,2,"c","abcd")   copyover(mydata, otherdata) // moredata1 = moredata1(1,1,c,abcd) 

note possible run problems si-7046, because of sealed trait (coproduct) type class derivation updaterepr, notice in repl or when splitting updaterepr , sealed traits on multiple files.


Comments

Popular posts from this blog

javascript - Slick Slider width recalculation -

jsf - PrimeFaces Datatable - What is f:facet actually doing? -

angular2 services - Angular 2 RC 4 Http post not firing -