Scala - extends vs with

前端 未结 3 1176
渐次进展
渐次进展 2021-01-31 16:02

I am confused. In my existing project, I am not able to find the difference between extends and with. Could you please help me?

3条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-31 16:27

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

    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 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. use of trait and (abstract) class is here;
    2. The resolution rule is the so-called class linearization; there is a post about it.

提交回复
热议问题