O'Reilly logo

Scala Functional Programming Patterns by Atul S. Khot

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required