3

如果您有一个案例类,例如:

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

您有两个实例,例如:

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

是否可以将实例 1 合并到实例 2 中,字段 z 除外,这样结果将是:

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

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

我想要的是这样的:

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

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

编辑: 我的案例类有更多字段,除非我明确表示不合并字段,否则我希望默认行为合并字段。

4

4 回答 4

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)

只要您在同一个案例类的两个实例之间进行复制,并且字段是不可变的,就像默认情况下一样,这将满足您的需求。

于 2013-01-12T11:18:58.787 回答
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)
于 2013-01-12T00:49:59.857 回答
3

您可以通过柯里化的复制方法从自动复制中排除类参数:

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

这清楚地表明哪些是客户端设置的普通值字段,哪些是特殊字段。你不能不小心忘记提供一个特殊的字段。

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

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)
}
于 2013-01-12T13:41:52.597 回答
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")
于 2013-01-12T01:57:02.627 回答