使用shapeless scala合并两个不同case类的字段 [英] Using shapeless scala to merge the fields of two different case classes
问题描述
我想将两个不同案例类的字段合并为一个案例类.
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?
推荐答案
你可以使用 shapeless Generic
来做到这一点.
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))
提供的t
是Test
的实例,a
是Answer
的实例,ta
将是 TestWithAnswers
的一个实例.
Provided t
is an instance of Test
and a
is an instance of Answer
, ta
will be an instance of TestWithAnswers
.
快速解释:Generic
可以将 case 类转换为通用的 HList
表示.因此,根据您的类的结构,您可以简单地将 test 和 answer 都转换为一个 hlist,将这两个列表连接成一个列表,然后从中构建一个 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.
这是一个更简单的示例,您可以复制粘贴并在 REPL 中尝试
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")
这篇关于使用shapeless scala合并两个不同case类的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!