Scala特质基础
示例
这是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
热门推荐
10 感谢韩语老师祝福语简短
11 升职文案高级祝福语简短
12 花童结婚祝福语大全简短
13 向国庆送祝福语简短
14 什么寄语简短祝福语女生
15 客户回礼祝福语大全简短
16 女孩生日祝福语简短创意
17 家长回复节日祝福语简短
18 给外婆敬酒祝福语简短