我试图使用type字段,但似乎做错了什么。它似乎在使用经典类,但由于某种原因,case类的apply类型并不匹配。
object Common {
type EntityId = Long
}
import Common._
abstract class IdStore {
self =>
type Entity
type Ref <: IdRef[_]
type Self <: IdStore {type Entity = self.Entity; type Ref = self.Ref}
def apply(data: Map[Ref, Entity]): Self
def data: Map[Ref, Entity]
def merge(other: Self): Self = apply(data ++ other.data)
}
trait IdRef[T] {
def id: T
}
trait EntityIdRef extends IdRef[EntityId] {}
class TestStore(val data: Map[IdRef[Int], Object]) extends IdStore {
override type Entity = Object
override type Ref = IdRef[Int]
override type Self = TestStore
override def apply(data: Map[Ref, Entity]): Self = new TestStore(data)
}
case class TestCaseClassStore(data: Map[IdRef[Int], Object]) extends IdStore {
override type Entity = Object
override type Ref = IdRef[Int]
override type Self = TestCaseClassStore
}错误
Main.scala:34: error: class TestCaseClassStore needs to be abstract, since method apply in class IdStore of type (data: Map[TestCaseClassStore.this.Ref,TestCaseClassStore.this.Entity])TestCaseClassStore.this.Self is not defined
case class TestCaseClassStore(data: Map[IdRef[Int], Object]) extends IdStore {
^
one error found代码也可在艾德龙上使用。
发布于 2016-02-14 11:24:15
我怀疑你搞错了关于案例课的一个细节:
Case类不附带免费的应用功能!
它们附带了一个配套对象,该对象具有一个工厂apply函数,用于创建case类的新实例。这就是:
case class Foo(bar: Int)类似于
class Foo(val bar: Int)
object Foo {
def apply(bar: Int): Foo = new Foo(bar)
}所以,在你的代码中
case class TestCaseClassStore(data: Map[IdRef[Int], Object]) extends IdStore {
override type Entity = Object
override type Ref = IdRef[Int]
override type Self = TestCaseClassStore
}缺少IdStore中所需的IdStore函数。
考虑到这一点,您确定在apply中定义的IdStore函数是您想要的吗?
发布于 2016-02-14 10:05:23
错误消息说--我认为这是正在发生的--是您对所有类型的IdStore进行了覆盖,但是没有为“应用”方法这样做。
对于"TestStore“类来说,它是正确的,但在"TestCaseClassStore”中则不是这样。
发布于 2016-02-14 11:23:19
这只是因为case class没有apply()方法。它的伙伴对象获得一个apply方法,而不是类。
但是,为了解决问题,我们需要更多地了解IdStore及其子类的预期使用情况。假设IdStore是完美的,那么您可能一开始就不希望TestCaseClassStore成为case class。
https://stackoverflow.com/questions/35390498
复制相似问题