2015-05-19 57 views
0

所以我試圖爲Scala實現Builder pattern的一個版本,我遇到了一些返回類型的問題。這裏是我的問題:Scala:構建器模式的返回運行時對象類型

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的聲明是可能的嗎?

回答

1

基本上,你只需要說Car.setFuelConsumption不返回不僅僅是一輛汽車,而是返回自身的類型,就像這樣:

def setFuelConsumption(con: Double): this.type = { 
    fuelConsumption = con 
    this 
} 
+0

謝謝!更多細節可以在[this]中找到(http://stackoverflow.com/questions/4313139/how-to-use-scalas-this-typing-abstract-types-etc-to-implement-a-self-type)回答 – Bar