Search code examples
scalaclassinstantiation

How do I instantiate a Scala case class using all the attributes of a smaller case class?


I have an instance of a case class A:

case class A(
  foo: String,
  bar: String,
  baz: String
)
val a = A("a", "b", "c")

I want to use this to create an instance of a case class B, with attributes that are a superset of A:

case class B(
  foo: String,
  bar: String,
  baz: String,
  qux: String,
  quux: String
)

Is there a more elegant way to do this than val b = (A.foo, A.bar, A.baz, "d", "e") ? I have to do this a few times in my code, and my actual use case has something like 20 parameters, so doing it the obvious way is very long-winded.


Solution

  • Firstly, a case class with 20 parameters is usually a sign of bad design, so think about grouping those parameters into smaller classes and then putting them together in a container class.

    If you keep this design and don't want to use external libraries, you can make a constructor for B that takes A plus the extra parameters:

    object B {
      def apply(a: A, qux: String, quux: String): B = B(a.foo, a.bar, a.baz, qux, quux)
    }
    
    val a:A = ???
    val b = B(a, "qux", "quux")