Scala-扩展与 [英] Scala - extends vs with

查看:81
本文介绍了Scala-扩展与的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很困惑.在我现有的项目中,我找不到extendswith之间的区别.你能帮我吗?

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 /traitwith s.

If you have multiple classes or traits to inherit, the first one is always extends, and the following >=0 class/trait to be withs.

但是请记住,您只能 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 extended, 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:

  1. trait和(abstract)class的用法是 此处
  2. 解决规则就是所谓的 类线性化;有关于它的帖子.. li>
  1. use of trait and (abstract) class is here;
  2. The resolution rule is the so-called class linearization; there is a post about it.

这篇关于Scala-扩展与的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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