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 Donkey horse.walk() // 7 donkey.walk() donkey.moveGoods() }
The salient points of the preceding code are as follows:
In the code, we defined a
NameIt
trait. This is very similar to a Java interfaceWe then declared...