我有两个特征,每个特征都有一个成员的类型参数.在第一个特征中,我有一个函数,它接受第二个特征的实例和第二个特征的类型成员的实例.此函数调用第二个特征中的函数,该函数期望其类型成员的实例.但是,我无法弄清楚如何正确地参数化调用,以便这实际上有效.这是一个失败的简化示例:
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
Run Code Online (Sandbox Code Playgroud)
此操作失败,并显示以下错误:
error: type mismatch;
found : fuel.type (with underlying type Garage.this.CarType#FuelType)
required: car.FuelType
copy(Cars.updated(car_index, car.Refuel(fuel)))
^
Run Code Online (Sandbox Code Playgroud)
如何约束Garage.Refuel函数以使其接受a Car和Fuel该类型可接受的任何函数Car?
尝试:
def Refuel(car: CarType)(fuel: car.FuelType): Garage = {
Run Code Online (Sandbox Code Playgroud)