Scala 相关特征、抽象类型

发布于 2024-12-05 02:32:56 字数 625 浏览 1 评论 0原文

我有两个相关的特征。 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

栖竹 2024-12-12 02:32:56

companion 的类型为 DaoHelper[T],但 T 未在 D 中的任何位置指定,那么编译器如何知道它应该是 D 类中的 D?您可以通过在 D 中覆盖它来修复它。

class D extends Dao {
  type T = D
  val companion = 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 extends Dao {
  type T = D
  val companion = D
}
笑,眼淚并存 2024-12-12 02:32:56

我不太明白您想对 class D 做什么,但您收到此错误是因为您将 D 分配给 companionclass 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 assigning D to companion in class D, but companion has type DaoHelper[T] as defined in Dao. Since D has type Dao and Dao is not a subtype of DaoHelper[T], this will not work.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文