特質基礎知識
這是 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"
}
由於沒有為特徵 Identifiable 宣告超類,因此預設情況下它從 AnyRef 類擴充套件。因為在 Identifiable 中沒有提供 getIdentifier 的定義,所以 Puppy 類必須實現它。然而,Puppy 繼承了 Identifiable 的 printIdentification 的實現。
在 REPL 中:
val p = new Puppy("K9", "Rex")
p.getIdentifier // res0: String = Rex has id K9
p.printIndentification() // Rex has id K9