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

Traits – Scala's rich interfaces

It would be super cool if we could write reusable code as well as get rid of the dreaded diamond. Scala's traits is the answer if we want to do this.

Here is how we could implement the preceding hierarchy in Scala:

object RichInterfaces extends App {
  trait NameIt { // 1
    def name(): String // 2
  }
  trait Walks extends NameIt { // 3
    def walk() = // 4
    println(name() + "" is having a stroll now"")
  }
  trait GoodsMover extends NameIt {
  def moveGoods() =
    println(name() + "" busy moving heavy stuff"")
  }
  class Horse extends Walks { // 5
    override def name(): String = ""Horse""
  }
  class Donkey extends Walks with GoodsMover { // 6
    override def name(): String = ""Donkey""
  }

  val horse = new Horse
 val donkey = new ...

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