Using shapeless scala to merge the fields of two different case classes

南笙酒味 提交于 2020-01-12 18:34:14

问题


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?


回答1:


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")


来源:https://stackoverflow.com/questions/31681784/using-shapeless-scala-to-merge-the-fields-of-two-different-case-classes

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!