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

你离开我真会死。 提交于 2019-12-04 04:18:53

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