Mix-ins – rich interfaces
Let's add a funny twist to the tale. We will now remove the NameIt
trait and change both the traits, as shown in the following code:
trait Walks { def name : String def walk() = println(name + "" is having a stroll now"") } trait GoodsMover { def name : String def moveGoods() = println(name + "" busy moving heavy stuff"") }
The name()
method, referred to by the traits, must be defined somewhere. As long as Horse
and Donkey
define the name()
method, it works.
Writing a rating comparison algorithm for our animals illustrates one major use of the traits. Our rating is a simple number. Try the following snippet to implement the compare
method:
object CompareAnimals extends App { // traits Walks and GoodsMover not shown abstract class Animal(val rating: Int) extends Ordered[Animal] class Horse(rating: Int) extends Animal(rating) with Walks { // 1 override def name(): String = ""Horse"" override def compare(that: Animal...