将一个案例类转换为具有相同结构但具有一个附加字段的另一个案例类

时间:2019-04-02 13:11:37

标签: scala

假设我有两个案例类:

case class C1(a: Int, b: String)
case class C2(a: Int, b: String, c: Long = 0)

我想将C1的实例转换为C2,然后设置其他字段c。我发现了以下解决方案:

C1.unapply(C1(1, "s1")).map(v => C2(v._1, v._2, 7l))

但是一一指定参数是不适用的,因为实际案例类将至少具有15个参数。有什么解决方法的想法吗?

2 个答案:

答案 0 :(得分:4)

可以通过执行类似此线程的操作来完成此解决方案。

How to append or prepend an element to a tuple in Scala

implicit class TupOps2[A, B](val x: (A, B)) extends AnyVal {
  def :+[C](y: C) = (x._1, x._2, y)
  def +:[C](y: C) = (y, x._1, x._2)
}

用法:

val c1      = new C1(1, "s1")
val longVal = 0L

scala> C1.unapply(c1).map(r => (r :+ longVal))
res0: Option[(Int, String, Long)] = Some((1,s1,0))

scala> C1.unapply(c1).map(r => (C2.apply _) tupled (r:+ longVal))
res45: Option[C2] = Some(C2(1,s1,0))

希望它会有所帮助:)

答案 1 :(得分:1)

我认为您需要的是

https://github.com/scalalandio/chimney

case class MakeCoffee(id: Int, kind: String, addict: String)
case class CoffeeMade(id: Int, kind: String, forAddict: String, at: ZonedDateTime)

val command = MakeCoffee(id = Random.nextInt,
                         kind = "Espresso",
                         addict = "Piotr")

import io.scalaland.chimney.dsl._

val event = command.into[CoffeeMade]
  .withFieldComputed(_.at, _ => ZonedDateTime.now)
  .withFieldRenamed(_.addict, _.forAddict)
  .transform