Scala-扩展与 [英] Scala - extends vs with
问题描述
我很困惑.在我现有的项目中,我找不到extends
和with
之间的区别.你能帮我吗?
I am confused. In my existing project, I am not able to find the difference between extends
and with
. Could you please help me?
推荐答案
如果您要继承多个class
es或trait
,则第一个始终为extends
,随后的> = 0 trait
为with
s.
If you have multiple class
es or trait
s to inherit, the first one is always extends
, and the following >=0 class
/trait
to be with
s.
但是请记住,您只能 inherit < = 1(抽象)类,这意味着如果您需要继承父类(Parent
),则它应始终位于第一个格式为... extends Parent ...
,则不能再将其他类继承到派生类.
But remember that you can only inherit <=1 (abstract) class, which means if you need to inherit a parent class (Parent
), it should always comes at first of the form ... extends Parent ...
, and no more classes can be inherited to the derived class.
trait T1
trait T2
class P1
class P2
class C1 extends T1
class C2 extends T1 with T2
class C3 extends T2 with T1
class C4 extends P1 with T1
/// class C5 extends T1 with P1 // invalid
/// class C6 extends P1 with P2 // invalid
实际上,
with
绑定到extend
的类/特征,例如class C7 extends P1 with T1 with T2
读取class C7 extends (P1 with T1 with T2)
.
with
is in fact bound to the class/trait that is extend
ed, e.g., class C7 extends P1 with T1 with T2
reads class C7 extends (P1 with T1 with T2)
.
请注意,这仅是从 语法 的角度出发, 语义 的差异可以从以下:
Note that this is only from the viewpoint of syntax, the semantic differences can be referred from the followings:
- use of
trait
and (abstract
)class
is here; - The resolution rule is the so-called class linearization; there is a post about it.
这篇关于Scala-扩展与的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!