继承一个特征两次 [英] Inheriting a trait twice

查看:106
本文介绍了继承一个特征两次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这不起作用:

trait Trait
class Class extends Trait with Trait

编译器投诉:

<console>:8: error: trait Trait is inherited twice
       class Class extends Trait with Trait
                           ^
<console>:8: error: trait Trait is inherited twice
       class Class extends Trait with Trait
                                      ^

这样做:

trait Trait
class Abstraction extends Trait
class Implementation extends Abstraction with Trait

问题:


  • 为什么会这样?

  • 第二个片段有何不同? (关于双继承问题)

  • 第二个片段或模式是否有用?

推荐答案

第二个片段因特征线性化而起作用。编译器会将特征组织成一个线性列表,这样 Trait 只出现一次。我认为线性化是

Second snippet works because of trait linearization. The compiler will organize the traits into a linear list so that Trait only appears once. I think the linearization is

Implementation, Trait, Abstraction, ScalaObject, AnyRef, Any

本章来自Programming Scala的一个很好的解释。

See this chapter from Programming Scala for a great explanation.

这主要是为了对钻石继承问题采用一致的方法,并且在这种情况下很有用。

This is primarily done to have a consistent approach to the diamond inheritance problem and is useful in that case.

由于 Trait 在线性化后无法出现两次,因此编写 Trait with Trait 并且禁止它是有意义的。

Since Trait cannot appear twice after linearization, it does not make sense to write Trait with Trait and it makes sense to be disallowed.

这篇关于继承一个特征两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆