【问题标题】:Scala compiler behaviour for Covariance协方差的 Scala 编译器行为
【发布时间】:2021-01-21 04:52:53
【问题描述】:

以下代码运行良好:

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

【问题讨论】:

    标签: scala types type-inference covariance


    【解决方案1】:

    因为推理可以从上下文中找出应该是什么类型。即

    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 compile
    

    【讨论】:

      猜你喜欢
      • 2016-08-24
      • 2016-10-16
      • 1970-01-01
      • 2012-06-29
      • 1970-01-01
      • 2017-07-26
      • 2018-08-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多