I have a case class with 25 fields and need to convert it into another with 22, of which 19 of these are shared and 3 are simply renamed.
I have found a few examples of how to do this using shapeless
(e.g. an answer here and some code examples from Miles Sabin here and here) but the last of those looks a bit out of date, and I can't figure out from the Github example how I can use shapeless to rename multiple fields, or do more manipulation on a field before adding it to the new object. Can anyone help me out?
Simplified code example;
import shapeless.LabelledGeneric
case class A(fieldA:Int, fieldB:String, fieldC:String)
case class B(fieldARenamed:Int, fieldB:String, fieldC:String, fieldCTransformed:String)
val aGen = LabelledGeneric[A]
val bGen = LabelledGeneric[B]
val freddie = new A(1,"Freddie","somestring")
val record = aGen.to(freddie)
val atmp = freddie.fieldA
record.Remove("fielda")
val freddieB = bGen.from(record +
(Symbol("fieldARenamed") ->> atmp) +
(Symbol("fieldCTransformed") ->> freddie.fieldC.toUpperCase)
) //Errors everywhere, even if I replace + with :: etc.
I have a feeling Align
is going to come into the picture somewhere here, but understanding how to do this in the leanest possible fashion - e.g. without creating additional traits like Field
, as in that third link above - would be interesting.
In The Shapeless Guide, there is also some usage of a single quote, (e.g. 'fieldC
) notation, which I haven't been able to find much information on, so if that plays a role some explanation would also be really helpful. Fairly new to this depth of Scala sorcery, so apologies if the question seems obtuse or covers too many disparate topics.
EDIT: For the avoidance of doubt, I am not looking for answers which suggest that I just manually create a new case class by referencing fields from the first, as in;
val freddieB = B(fieldARenamed = freddie.fieldA, fieldB = freddie.fieldB, fieldC = freddie.fieldC, fieldCTransformed =freddie.fieldC.toUpperCase)
See below comment for various reasons why this is inappropriate.