Traits
Many of you might have different perspectives of traits in Scala. They can be viewed not only as interfaces in other languages, but also as classes with only parameter-less constructors.
Tip
Trait parameters
The Scala programming language is quite dynamic and it has evolved quickly. One of the directions that will be investigated for the 2.12 version of the language are trait parameters. More information can be found at http://www.scala-lang.org/news/roadmap-next/.
In the following few sections, we will we will see the traits from different points of view and try to give you some ideas about how they can be used.
Traits as interfaces
Traits can be viewed as interfaces in other languages, for example, Java. They, however, allow the developers to implement some or all of their methods. Whenever there is some code in a trait, the trait is called a mixin. Let's have a look at the following example:
trait Alarm { def trigger(): String }
Here Alarm
is an interface. Its only method, trigger...