Using formless scala to combine the fields of two different case classes

I want to combine the fields of two different case classes into one case class.

For example, if I have the following case classes:

case class Test(name:String, questions:List[Question], date:DateTime) case class Answer(answers:List[Answers]) 

I want a concise formless way to combine both:

 TestWithAnswers(name:String, questions:List[Question], date:DateTime, answers:List[Answer]). 

Is there a good shapeless answer?

+6
source share
1 answer

You can use shapeless Generic for this.

 val t: Test = ??? val a: Answer = ??? val gt = Generic[Test] val ga = Generic[Answer] val gta = Generic[TestWithAnswers] val ta = gta.from(gt.to(t) ++ ga.to(a)) 

or well if you have a thing for single-line objects

 val ta = Generic[TestWithAnswers].from(Generic[Test].to(t) ++ Generic[Answer].to(a)) 

If t is an instance of Test and a is an instance of Answer , ta will be an instance of TestWithAnswers .

Brief explanation: Generic can convert the case class to and from the general view of HList . So, given the structure of your classes, you can simply convert both tests and respond to an hlist, combine the two lists into one, and build an instance of TestWithAnswers from it.

Here is a simpler example that you can copy-paste and try in REPL

 import shapeless._ case class A(a: Int) case class B(a: String) case class AB(a: Int, b: String) Generic[AB].from(Generic[A].to(A(42)) ++ Generic[B].to(B("foo"))) // AB(42, "foo") 
+10
source

All Articles