合并两个相同类型的案例类,但某些字段除外

时间:2013-01-12 00:42:55

标签: scala case-class

如果你有一个类似的案例类:

case class Foo(x: String, y: String, z: String)

你有两个例子:

Foo("x1","y1","z1")
Foo("x2","y2","z2")

是否可以合并实例2中的实例1,但字段z除外,因此结果为:

Foo("x1","y1","z2")

我的用例就是我通过Scala API将JSON对象提供给Backbone应用程序,而Backbone应用程序为我提供了相同结构的JSON,以便我可以保存/更新它。这些JSON对象被解析为案例类,以便于Scala操作。但是客户端永远不应该更新某些字段(如creationDate)。现在我正在进行手动合并,但我想要一个更通用的解决方案,有点像增强的复制功能。

我想要的是这样的:

instanceFromDB.updateWith(instanceFromBackbone, excludeFields = "creationDate" )

但我希望它是类型安全的:)

修改 我的case类有很多字段,我想要合并字段的默认bevavior,除非我明确说不合并它们。

4 个答案:

答案 0 :(得分:4)

你想要的是什么;你只需要以另一种方式解决问题。

case class Bar(x: String, y: String)
val b1 = Bar("old", "tired")
val b2 = Bar("new", "fresh")

如果您希望未明确提及b2中的所有内容,则应从b2复制;您想要保留的b1中的任何内容都可以明确提及:

def keepY(b1: Bar, b2: Bar) = b2.copy(y = b1.y)

scala> keepY(b1, b2)
res1: Bar = Bar(new,tired)

只要您在同一个案例类的两个实例之间进行复制,并且这些字段在默认情况下是不可变的,这将完成您想要的操作。

答案 1 :(得分:3)

case class Foo(x: String, y: String, z: String)

Foo("old_x", "old_y", "old_z")
// res0: Foo = Foo(old_x,old_y,old_z)

Foo("new_x", "new_y", "new_z")
// res1: Foo = Foo(new_x,new_y,new_z)

// use copy() ...
res0.copy(res1.x, res1.y)
// res2: Foo = Foo(new_x,new_y,old_z)

// ... with by-name parameters
res0.copy(y = res1.y)
// res3: Foo = Foo(old_x,new_y,old_z)

答案 2 :(得分:3)

您可以通过currying方法通过复制方法从自动复制中排除类参数:

case class Person(name: String, age: Int)(val create: Long, val id: Int)

这清楚地说明了客户端设置的普通值字段和特殊字段。你不能不小心忘记提供一个特殊领域。

对于从一个实例获取值字段而从另一个实例获取特殊字段的用例,通过使用默认args或原始特殊成员反射调用副本:

import scala.reflect._
import scala.reflect.runtime.{ currentMirror => cm }
import scala.reflect.runtime.universe._
import System.{ currentTimeMillis => now }

case class Person(name: String, age: Int = 18)(val create: Long = now, val id: Int = Person.nextId) {
  require(name != null)
  require(age >= 18)
}
object Person {
  private val ns = new java.util.concurrent.atomic.AtomicInteger
  def nextId = ns.getAndIncrement()
}

object Test extends App {

  /** Copy of value with non-defaulting args from model. */
  implicit class Copier[A: ClassTag : TypeTag](val value: A) {
    def copyFrom(model: A): A = {
      val valueMirror = cm reflect value
      val modelMirror = cm reflect model
      val name = "copy"
      val copy = (typeOf[A] member TermName(name)).asMethod

      // either defarg or default val for type of p
      def valueFor(p: Symbol, i: Int): Any = {
        val defarg = typeOf[A] member TermName(s"$name$$default$$${i+1}")
        if (defarg != NoSymbol) {
          println(s"default $defarg")
          (valueMirror reflectMethod defarg.asMethod)()
        } else {
          println(s"def val for $p")
          val pmethod = typeOf[A] member p.name
          if (pmethod != NoSymbol) (modelMirror reflectMethod pmethod.asMethod)()
          else throw new RuntimeException("No $p on model")
        }
      }
      val args = (for (ps <- copy.paramss; p <- ps) yield p).zipWithIndex map (p => valueFor(p._1,p._2))
      (valueMirror reflectMethod copy)(args: _*).asInstanceOf[A]
    }
  }
  val customer  = Person("Bob")()
  val updated   = Person("Bobby", 37)(id = -1)
  val merged    = updated.copyFrom(customer)
  assert(merged.create == customer.create)
  assert(merged.id == customer.id)
}

答案 3 :(得分:1)

case class Foo(x: String, y: String, z: String)

val foo1 = Foo("x1", "y1", "z1")
val foo2 = Foo("x2", "y2", "z2")

val mergedFoo = foo1.copy(z = foo2.z) // Foo("x1", "y1", "z2")

如果您稍后将Foo更改为:

case class Foo(w: String, x: String, y: String, z: String)

不需要进行任何修改。明确地:

val foo1 = Foo("w1", "x1", "y1", "z1")
val foo2 = Foo("w2", "x2", "y2", "z2")

val mergedFoo = foo1.copy(z = foo2.z) // Foo("w1", "x1", "y1", "z2")