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 ...

Get Scala Functional Programming Patterns now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.