What are traits ?
Traits are a fundamental unit of code reuse in Scala. A
trait encapsulates method and ﬁeld deﬁnitions, which
can then be reused by mixing them into classes.
Traits are a way to inherit from multiple class-like
constructs, but they differ in important ways from the
multiple inheritance present in many languages. One
difference is especially important: the interpretation of
How traits work ?
Once a trait is deﬁned, it can be mixed in to a class using
either the extends or with keywords.
Mixing multiple Traits
Override Trait methods as shown below
Are trait like Java Interface ?
Traits are like Java interfaces but with concrete
methods, but they can actually do much more. Traits
can, for example, declare ﬁelds and maintain state.
Scala's Stackable Trait
Let us look at example
When to use traits ?
If the behavior will not be reused, then make it a concrete class.
If efﬁciency is very important, lean towards using a class.Most Java
runtimes make a virtual method invocation of a class member a
faster operation than an interface method invocation. Traits get
compiled to interfaces and therefore may pay a slight performance
If it might be reused in multiple, unrelated classes, make it a trait.
If you still do not know, after considering the above, then start by
making it as a trait. You can always change it later, and in general
using a trait keeps more options open.
Credits and Reference
Odersky, Martin; Spoon, Lex;
Venners, Bill (2010-12-13).
Programming in Scala: A
Guide (Kindle Location 4334).
Artima Press. Kindle Edition.
Thanks to Constantine for feedback
,app design and code clean up