I am confused. In my existing project, I am not able to find the difference between extends
and with
. Could you please help me?
In Scala, you can inherit from class
es (concrete or abstract
) and trait
s. In a similar way to how you can extend only one class, but implement as many interfaces as you'd like in Java, you're only allowed to inherit from one class
, but as many trait
s as you'd like.
If you are extending a class
, that class should immediately follow the extends
keyword. Any trait
s you are extending from should follow, separated by with
keywords.
If you are not extending a class, you can put your first trait
right after the extends
keyword and continue after that.
Just as in Java, every class is a subclass of Object
whether you explicitly declare it or not, every (user-defined) class in Scala extends AnyRef with ScalaObject
whether or not you include that explicitly.
The following sets of declarations are therefore equivalent:
class MyClass { ... }
class MyClass extends AnyRef with ScalaObject { ... }
class MyClass extends MySuperClass { ... }
class MyClass extends MySuperClass with ScalaObject { ... }
class MyClass extends MyTrait1 with MyTrait2 { ... }
class MyClass extends AnyRef with MyTrait1 with MyTrait2 { ... }
class MyClass extends MySuperClass with MyTrait1 with MyTrait2 { ... }
The last example is not the same if you change the order of MySuperClass
, MyTrait1
, and MyTrait2
. In particular, you cannot put a trait in front of a class and the order in which you stack traits is important if they both have implementations for the same methods. (In that case, the last one "wins".)
Remember also that only class
es in Scala can have parameters, so you'll only ever be able to attach parameters to the type after the extends
keyword, never to any of the types listed after with
.
Hope that helps!