以下代码运行良好:
abstract class Vehicle{
val name:String
}
case class Car(name: String) extends Vehicle
case class Bike(name: String) extends Vehicle
case class Parking[T](vehicle: T)
object Covariance extends App {
def parkMyVehicle(p : Parking[Vehicle]): Unit = println(s"Parking ${p.vehicle.name}")
parkMyVehicle(Parking(Car("Mercedes")))
parkMyVehicle(Parking(Bike("HD")))
}这有点奇怪,因为Parking不是协变的。
但是,下面这一行要求协变量Parking,否则不能编译(这是预期的)。
parkMyVehicle(Parking[Car](Car("Mercedes")))我的问题是,为什么parkMyVehicle(Parking(Car("Mercedes")))不要求协变Parking
发布于 2020-10-06 10:21:35
因为推断可以从上下文中确定应该是什么类型。也就是说。
parkMyVehicle(Parking(Car("Mercedes")))
// ^ ---------------------^ What's the type of that?由于parkMyVehicle采用Parking[Vehicle],所以这种类型应该来自编译器PoV。因此,该表达式将被键入一个向上转换到超类:
parkMyVehicle(Parking[Vehicle](Car("Mercedes"): Vehicle))但是,如果提取变量,则情况会有所不同:
val p = Parking(Car("Mercedes")) // Type is first figured out to be Parking[Car]
parkMyVehicle(p) // now the type of p does not match, so it fails to compilehttps://stackoverflow.com/questions/64223601
复制相似问题