因此,我尝试为Scala实现Builder pattern的版本,并且我的返回类型遇到了一些问题。这是我的问题:
abstract class Car() {
protected var fuelConsumption = 10.0
def setFuelConsumption(con: Double): Car = {
fuelConsumption = con
this
}
}
trait HasHorn extends Car {
protected var hornSound = "Toot!"
def setHornSound(sound: String): HasHorn = {
hornSound = sound
this
}
}
class ModelT extends Car with HasHorn
// I can do this:
val aCar = new ModelT().setHornSound("Beep!").setFuelConsumption(5.0)
// But not this, because setFuelConsumption returns a Car
val bCar = new ModelT().setFuelConsumption(12.0).setHornSound("Beep!")
所以我的问题是:如何返回对象的运行时类型,以便可以像bCar这样的声明?
答案 0 :(得分:1)
基本上,你只需要说Car.setFuelConsumption不会返回Car,而是返回它自己的类型,如下所示:
def setFuelConsumption(con: Double): this.type = {
fuelConsumption = con
this
}