This is the most basic version of a trait in Scala.
trait Identifiable {
def getIdentifier: String
def printIndentification(): Unit = println(getIdentifier)
}
case class Puppy(id: String, name: String) extends Identifiable {
def getIdentifier: String = s"$name has id $id"
}
Since no super class is declared for trait Identifiable
, by default it extends from AnyRef
class. Because no definition for getIdentifier
is provided in Identifiable
, the Puppy
class must implement it. However, Puppy
inherits the implementation of printIdentification
from Identifiable
.
In the REPL:
val p = new Puppy("K9", "Rex")
p.getIdentifier // res0: String = Rex has id K9
p.printIndentification() // Rex has id K9