I want to merge the fields of two different case classes into a single 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 shapeless way to merge both into:
TestWithAnswers(name:String, questions:List[Question], date:DateTime, answers:List[Answer]).
Is there a nice shapeless answer out there?
答案 0 :(得分:12)
You can use shapeless Generic
to do 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 one-liners
val ta = Generic[TestWithAnswers].from(Generic[Test].to(t) ++ Generic[Answer].to(a))
Provided t
is an instance of Test
and a
is an instance of Answer
, ta
will be an instance of TestWithAnswers
.
A quick explanation: Generic
can convert a case class to and from a generic HList
representation. So, given the structure of your classes, you can simply convert both test and answer to an hlist, concatenate the two lists into a single one and build a TestWithAnswers
instance from it.
Here's a simpler example, which you can copy-paste and try in a 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")