Sumeet Kumar Yadav
Sumeet Kumar Yadav

Reputation: 13015

Copy attributes from case class

case class A(a:Int ,b:Int,c:Int,d:Int)

case class B(a:Int ,b:Int,c:Int,d:Int,e:List[Int],f:List[Int])

val a = A(1,2,3,4)

val b = B(a.a,a.b,a.c,a.d,List(1,2),List(2,3))

Currently, I am manually copying class A object to B like a.a, a.b, a.c, a.d

Is there any alternate way to do something like

val b = B(a.attributes.toList,List(1,2),List(2,3))

Upvotes: 1

Views: 361

Answers (4)

cubic lettuce
cubic lettuce

Reputation: 6579

There are some Scala libraries that focus on typesafe, boilerplate-free copying between case classes. I like Chimney:

https://scalalandio.github.io/chimney/

You can do as follows:

  case class A(a:Int,b:Int,c:Int,d:Int)
  case class B(a:Int,b:Int,c:Int,d:Int,e:List[Int],f:List[Int])

  val a = A(1,2,3,4)

  // if additional parameters e and f in B would have default values
  val b1 = a.transformInto[B]

  // explicitly set additional parameters in B to constant values
  val b2 = a.into[B]
            .withFieldConst(_.e, List(1,2))
            .withFieldConst(_.f, List(1,2))
            .transform

Upvotes: 2

Dhirendra
Dhirendra

Reputation: 309

try this `

 case class A(a:Int, b:Int, c:Int, d:Int)

 case class B(a:List[Any], e:List[Int], f:List[Int])


 val a = A(1,2,3,4)

 val b = B(a.productIterator.toList,List(1,2),List(2,3))

`

Upvotes: 1

jwvh
jwvh

Reputation: 51271

If you have access and control of the B code then you can add as many different constructors as you like.

case class A(a:Int, b:Int, c:Int, d:Int)

case class B(a:Int ,b:Int,c:Int,d:Int,e:List[Int],f:List[Int])

object B {
  def apply(a:A, e:List[Int], f:List[Int]) = new B(a.a, a.b, a.c, a.d, e, f)
}

val a = A(1,2,3,4)

val b1 = B(a.a, a.b, a.c, a.d, List(1,2), List(2,3))
val b2 = B(a, List(4,5), List(9,1))

If you can't, or would rather not, modify A or B then you might add one or more implicit conversion methods.

implicit class A2B(a:A) {
  def toB(e:List[Int], f:List[Int]) :B = B(a.a, a.b, a.c, a.d, e, f)
}
val a = A(1,2,3,4)

val b1 = B(a.a, a.b, a.c, a.d, List(1,2), List(2,3))
val b3 = a.toB(List(32,12), List(544,2))

Upvotes: 3

Dhirendra
Dhirendra

Reputation: 309

Try This

case class A(a:Int, b:Int, c:Int, d:Int)

case class B(a:A, e:List[Int], f:List[Int])

val a = A(1,2,3,4)

val b = B(a,List(1,2),List(2,3))

Upvotes: 0

Related Questions