案例类的复制方法似乎缺失了

时间:2016-02-14 20:16:19

标签: scala case-class

我无法理解在案例类copy中未创建/获取TestCaseClassStore方法的原因。

abstract class IdStore {
  self =>
  type Entity
  type Ref <: IdRef[_]
  type Self <: IdStore {type Entity = self.Entity; type Ref = self.Ref}

  def copy(data: Map[Ref, Entity]): Self

  def data: Map[Ref, Entity]

  def merge(other: Self): Self = copy(data ++ other.data)
}

trait IdRef[T] {
  def id: T
}

case class IntIdRef(id:Int) extends IdRef[Int]

class TestStore(val data: Map[IntIdRef, Object]) extends IdStore {
  override type Entity = Object
  override type Ref = IntIdRef
  override type Self = TestStore

  override def copy(newData: Map[Ref, Entity]): Self = new TestStore(newData)

  override def toString() = "TestStore(" + data + ")"
}

case class TestCaseClassStore(data: Map[IntIdRef, Object]) extends IdStore {
  override type Entity = Object
  override type Ref = IntIdRef
  override type Self = TestCaseClassStore
}

object Main extends App {
    val data = Map(IntIdRef(1) -> "target 1", IntIdRef(2) -> "target 2"); 

    val classic = new TestStore(data)
    println(classic.copy(classic.data))

    val caseClass = new TestCaseClassStore(data)
    println(caseClass.copy(caseClass.data))
}

最终会出现未定义的方法错误:

Main.scala:30: error: class TestCaseClassStore needs to be abstract, since method copy in class IdStore of type (data: Map[TestCaseClassStore.this.Ref,TestCaseClassStore.this.Entity])TestCaseClassStore.this.Self is not defined
case class TestCaseClassStore(data: Map[IntIdRef, Object]) extends IdStore {
           ^
one error found

如果我在案例类中添加以下行,它可以工作,但它没用,因为我想使用案例类的主要原因是自动生成的复制方法。

  override def copy(newData: Map[Ref, Entity]): Self = TestCaseClassStore(newData)
  • 为什么copy上没有TestCaseClassStore方法?也许是编译器或语言的限制?或者我是否错误地实现了超类(但TestStore类正在运行)?

  • 是否有一些简洁的方式来编写IdStore的更多实现(最好不要重复copy方法,甚至以某种方式抽象Entity和{ {1}}构造函数中的类型,因此在类型定义中只提到一次)?

1 个答案:

答案 0 :(得分:0)

如果存在复制方法,编译器不会生成复制方法。

您可以看到,通过向超类中的copy-method添加实现,它不会被覆盖。我怀疑这是故意的。