Scala - 共同特征的第二代继承

发布于 2025-01-08 07:38:44 字数 412 浏览 3 评论 0原文

如果我在 Scala 中有以下代码:

trait A {
  var yo = 10
  def get = yo
}

trait B extends A { /* makes use of A.get */ }
trait C extends A { /* makes use of A.get */ }

trait D extends B with C { /* makes use of A.get */ }

class E extends D { /* makes use of A.get */ }

编译器将如何解决依赖关系?换句话说,它是否会理解,从两个不同的特征 B 和 C 继承的特征 D 和对象 E 的 A 特征相关部分必须被视为单个事物,而不是在每种继承情况下都重复?无论如何,在这种情况下编译器的想法会是什么样子?

If I have the following code in Scala:

trait A {
  var yo = 10
  def get = yo
}

trait B extends A { /* makes use of A.get */ }
trait C extends A { /* makes use of A.get */ }

trait D extends B with C { /* makes use of A.get */ }

class E extends D { /* makes use of A.get */ }

How will the compiler resolute the dependencies? In other words, will it understand that the A-trait related part of trait D and object E, inherited from the two different traits B and C has to be treated as a single thing, and not duplicated for every case of inheritance? In any way, what will the thoughts of the compiler look like in that situation?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

魔法唧唧 2025-01-15 07:38:44

根据 tenshi 的建议,从 Scala 编程的 这一章 中,我们得到以下内容例子:

class Animal 
trait Furry extends Animal
trait HasLegs extends Animal
trait FourLegged extends HasLegs
class Cat extends Animal with Furry with FourLegged

推导出以下管道:

Cat -> FourLegged -> HasLegs -> Furry -> Animal 

所以右边的人有优先权,但他的祖先,只要不是管道上其他人的共同祖先,也有优先权。这就是为什么 HasLegs 出现在 Furry 之前。

最后,这是您的特定示例的答案:

E -> D -> C -> B -> A 

From this chapter of Programming in Scala, as suggested by tenshi, we have the following example:

class Animal 
trait Furry extends Animal
trait HasLegs extends Animal
trait FourLegged extends HasLegs
class Cat extends Animal with Furry with FourLegged

Which derives into the following pipeline:

Cat -> FourLegged -> HasLegs -> Furry -> Animal 

So the one on the right has priority, but his ancestors, as long as they are not common ancestors of others on the pipeline, also have priority. This is why HasLegs comes before Furry.

Finally, here is the answer for your particular example:

E -> D -> C -> B -> A 
只涨不跌 2025-01-15 07:38:44

我相信,Scala 编程这一章可以帮助您理解特征线性化过程:

Scala 编程 - 12.6 为什么不采用多重继承?

I believe, that this chapter of Programming in Scala can help you in understanding of trait linearization process:

Programming in Scala - 12.6 Why not multiple inheritance?

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