0

This question is similar to this one, except that both case class instances need to be accessed with references to their base trait. The reason for this is that more than one case class will be extending the trait, and the exact type won't be known until runtime:

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

val from: baseData = data1(1,2)
val to: moreData =  moreData1(3,4,"a","b")

How to write a function with the following signature that copies from into to?

def copyOver[A <:baseData, B <:moreData](from: A, to: B)

I'm sure this is doable with Shapeless, but I'm having trouble since I'm pretty new to it.

Community
  • 1
  • 1
Cigogne Eveillée
  • 2,178
  • 22
  • 36
  • 1
    Case classes are immutable, so your `copyOver` signature doesn't make much sense. Could you give a concrete example of the `copyOver(from: data1, to: moreData1)` implementation? – dwickern Jul 21 '16 at 01:19
  • 1
    Also you can drop the `override val` keywords in your case class definitions – dwickern Jul 21 '16 at 01:20
  • `copyOver` wouldn't modify the case class instances, but create a new instance with the result. See here for an example using the cases classes directly without using trait references: https://github.com/milessabin/shapeless/wiki/Feature-overview:-shapeless-2.0.0#generic-representation-of-sealed-families-of-case-classes – Cigogne Eveillée Jul 21 '16 at 01:51
  • Seems I indeed didn't solve your problem completely in the [other question](http://stackoverflow.com/questions/38405782/scala-copying-a-generic-case-class-into-another). The difficult part is the evidence that all the types in the `Generic` `Coproduct` for `baseData` have the fields `weight` and `priority`. – Peter Neyens Jul 21 '16 at 08:23
  • It is hard to imagine how this would work at compile time. The input is represented by a `Coproduct`, and since it is not known which case class the input value belongs to, I don't know how it can be possible to implicitly resolve the `Generic` to convert it to a `HList`. Furthermore, when the return type is a sealed trait, the `copyOver` method has no idea which case class to instantiate. – devkat Aug 09 '16 at 07:31

0 Answers0