Assuming you have case classes like the following
case class Test1(a:String,b:Int,c:Char)
case class Test2(a:String,b:Int)
And you instantiate the classes with the following variables
val test1 = Test1("first",2,'3')
val test2 = Test2("1st",20)
Is there a way to use the .copy
method (or otherwise), to apply the variables inside Test2 to Test1, something like
val test3 = test1.copy(test2) //Note this isn't valid scala code
// Result should be ("1st",20,'3')
If this isn't possible in pure scala, how would it be done in Shapeless 1/2 (current code is in Shapeless 1, however we are planning to upgrade to Shapeless 2 at some point in time)
In shapeless 2.0.0 this can be done with like so,
Note that this makes assumptions about the order of fields in each of the case classes rather than making use of field label information. This could be error prone where you had multiple fields of the same type: the types might line up, but the latent semantics might be altered.
We can fix that by using shapeless's
LabelledGeneric
.LabelledGeneric
maps case class values to shapeless extensible records which, as well as capturing the types of the field values, also encodes the field names in the type by way of the singleton type of the corresponding ScalaSymbol
. With a little bit of additional infrastructure (which I'll be adding to shapeless 2.1.0 shortly) this allows us to map between case classes safely with minimal boilerplate,