这是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"
}由于没有为trait声明超类Identifiable,因此默认情况下它是从AnyRefclass扩展的。因为没有getIdentifier提供的定义Identifiable,所以Puppy该类必须实现它。然而,Puppy继承的实现printIdentification从Identifiable。
在REPL中:
val p = new Puppy("K9", "Rex")
p.getIdentifier // res0:字符串= Rex的ID为K9
p.printIndentification() // 雷克斯的ID为K9