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