这个例子是一个我试图解决的更大问题的模型。顶部的层次结构是抽象特征CarFamily,然后有3个从CarFamily延伸出来的抽象特征,即本田,思域和沃尔沃。我的目标是能够从这三个特征延伸出来的实例中为每个子特征调用carModelStatement。斯卡拉特质:通过在孩子中传递值不能获取抽象的父特征值
但是,正如您可以看到结果一样,这些语句都返回“汽车模型为空”。所以val volvo,honda,civic没有被传递给我是Scala的新手。想知道我错过了什么,或者如果有另一种设计来获得我想要的。谢谢!
trait CarFamily {
val carModel: String
def carModelStatement: String = s"The model of the car is ${carModel}"
}
trait Honda extends CarFamily {
val honda: String
override val carModel: String = honda
def hondaModelStatement : String = carModelStatement
}
trait Civic extends CarFamily {
val civic: String
override val carModel: String = civic
def civicModelStatement : String = carModelStatement
}
trait Volvo extends CarFamily {
val volvo: String
override val carModel: String = volvo
def volvoModelStatement : String = carModelStatement
}
object allModels extends Volvo with Civic with Honda {
val volvo = "Volvo X3"
val civic = "Civic Family"
val honda = "Honda Extreme"
}
allModels.volvoModelStatement //res1: String = The model of the car is null
allModels.civicModelStatement // res2: String = The model of the car is null
allModels.hondaModelStatement // res3: String = The model of the car is null
我怕,当你得到这个工作,你会发现,它并没有完全做到,你可能期待什么。 –