Scala 相关特征、抽象类型
我有两个相关的特征。 Dao 将作为一个类使用,DaoHelper 将由 Dao 的伴生对象使用。我希望 Trait Dao 能够使用 DaoHelper 中定义的函数,我能弄清楚如何做到这一点的唯一方法是将伴随特征定义为 val。然而不知何故,companion 期望它的类型是 D.this.T,我认为我已将其定义为 Doa 的子类型。我在这里很困惑。我对这个新手问题表示歉意,我来自动态语言背景。
/test2.scala:14: 重写类型 Test.DaoHelper[D.this.T] 的特征 Dao 中的值同伴; [错误] 伴随值的类型不兼容 [错误] val 同伴 = D
object Test extends App {
trait Dao {
type T <: Dao
val companion: DaoHelper[T]
def getHelpfulData = companion.help
}
trait DaoHelper[Dao] {
val help = "Some helpful data"
}
class D extends Dao {
val companion = D
}
object D extends DaoHelper[D]
}
I have 2 related traits. Dao will be used be a class and DaoHelper will be used by Dao's companion object. I would like trait Dao to be able use functions defined in DaoHelper, the only way I could figure out how to do this is to define the companion trait as a val. However somehow companion expects its type to be D.this.T which I thought I has defined as a subtype of Doa. I am confused here. My apologies for the newb question, I come from a dynamic language background.
/test2.scala:14: overriding value companion in trait Dao of type Test.DaoHelper[D.this.T];
[error] value companion has incompatible type
[error] val companion = D
object Test extends App {
trait Dao {
type T <: Dao
val companion: DaoHelper[T]
def getHelpfulData = companion.help
}
trait DaoHelper[Dao] {
val help = "Some helpful data"
}
class D extends Dao {
val companion = D
}
object D extends DaoHelper[D]
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
companion
的类型为 DaoHelper[T],但 T 未在 D 中的任何位置指定,那么编译器如何知道它应该是 D 类中的 D?您可以通过在 D 中覆盖它来修复它。companion
has type DaoHelper[T], but T isn't specified anywhere in D, so how would the compiler know it is supposed to be D in class D? You can fix it by overriding it in D.我不太明白您想对
class D
做什么,但您收到此错误是因为您将D
分配给companion
在class D
中,但companion
具有DaoHelper[T]
类型,如Dao
中定义。由于D
具有Dao
类型,并且Dao
不是DaoHelper[T]
的子类型,因此这不起作用。I don't quite understand what you are trying to do with
class D
, but you are getting this error because you are assigningD
tocompanion
inclass D
, butcompanion
has typeDaoHelper[T]
as defined inDao
. SinceD
has typeDao
andDao
is not a subtype ofDaoHelper[T]
, this will not work.