【问题标题】:Copy method of case class seems to be missing案例类的复制方法似乎丢失了
【发布时间】:2016-02-15 04:39:10
【问题描述】:

我无法理解为什么 copy 方法在 case class 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 方法,或者甚至以某种方式在构造函数中抽象 EntityRef 类型,所以它们在类型定义中只被提及一次)?

【问题讨论】:

    标签: scala case-class


    【解决方案1】:

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

    您可以看到,通过向超类中的复制方法添加一个实现,它不会被覆盖。我怀疑这是故意的。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-13
    • 2016-09-28
    • 2017-09-08
    • 1970-01-01
    • 2014-08-25
    • 1970-01-01
    • 2018-05-22
    • 1970-01-01
    相关资源
    最近更新 更多