简体   繁体   中英

Scala: Return run-time object type for builder pattern

So I'm trying to implement a version of the Builder pattern for Scala and I'm running into some trouble with my return types. Here's my problem:

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!")

So my question is: How can I return the runtime type of the object, so that a declaration like bCar is possible?

Basically, you just need to say that Car.setFuelConsumption does not return just a Car, but instead returns the type of itself, like so:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM