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 送给学长毕业祝福语简短