我有两个特征,每个特征都有一个为其成员之一的类型参数。在第一个特征中,我有一个函数,它采用第二个特征的实例和第二个特征的类型成员的实例。此函数调用第二个特征中的函数,该函数期望其类型成员的该实例。但是,我无法弄清楚如何正确参数化调用以使其真正起作用。这是一个失败的简化示例:
trait Garage {
type CarType <: Car
def Cars: Seq[CarType]
def copy(Cars: Seq[CarType]): Garage
def Refuel(car: CarType, fuel: CarType#FuelType): Garage = {
val car_index = Cars.zipWithIndex.find(_._1 == car).get._2
copy(Cars.updated(car_index, car.Refuel(fuel)))
}
}
trait Car {
type FuelType <: Fuel
def Fuel: FuelType
def copy(Fuel: FuelType): Car
def Refuel(fuel: FuelType): Car = {
copy(fuel)
}
}
trait Fuel
这失败并出现以下错误:
error: type mismatch;
found : fuel.type (with underlying type Garage.this.CarType#FuelType)
required: car.FuelType
copy(Cars.updated(car_index, car.Refuel(fuel)))
^
如何约束Garage.Refuel
函数以使其接受 aCar
以及Fuel
该类型可接受的任何Car
?