这是上一个问题的后续问题,其中我有一个类型 member 的特征Garage
,CarType
它本身有一个 type member FuelType
,我需要一个函数refuel
,它可以将 的实例CarType
作为第一个参数,并将第一个参数的实例FuelType
作为第二个论点。
下面的两个特征的答案是给出Car
一个表示类型C <: Car[C]
。我现在遇到的问题是我无法弄清楚如何在实现的具体类上定义类型参数Garage
,例如ConcreteGarage
下面。
trait Fuel
trait Garage {
type CarType <: Car[CarType]
def cars: Seq[CarType]
def copy(cars: Seq[CarType]): Garage
def refuel(car: CarType, fuel: CarType#FuelType): Garage = copy(
cars.map {
case `car` => car.refuel(fuel)
case other => other
})
}
trait Car[C <: Car[C]] {
type FuelType <: Fuel
def fuel: FuelType
def copy(fuel: C#FuelType): C
def refuel(fuel: C#FuelType): C = copy(fuel)
}
class ConcreteGarage(val cars: Seq[ConcreteGarage#CarType]) extends Garage {
type CarType = Car[CarType] // Nope
//type CarType = Car[Any] // Nope
//type CarType = Car[Nothing] // Nope
//type CarType = Car[Car] // Nope
//type CarType <: Car[CarType] // Nope
def copy(cars: Seq[CarType]) = new ConcreteGarage(cars)
}