【发布时间】: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方法,或者甚至以某种方式在构造函数中抽象Entity和Ref类型,所以它们在类型定义中只被提及一次)?
【问题讨论】:
标签: scala case-class