在Scala中,为什么在方法类型参数上设置下限类型的边界不对方法论点施加“是超类型”限制?

object TypeBounds extends App {
  class MotorVehicle
  class Truck extends MotorVehicle
  class Car extends MotorVehicle
  class Saloon extends Car
  class HatchBackSaloon extends Saloon

  def lowerTypeBound[C >: Car](c: C): C = c

  def upperTypeBound[C <: Car](c: C): C = c

  // Works. HatchBackSaloon is a sub class of Car
  println(upperTypeBound(new HatchBackSaloon()))

  // as expected doesn't compile. Truck is not a subclass of Car
  println(upperTypeBound( new Truck()))

  // Compiles and runs, but why ?  HatchBackSaloon is not a super class of Car.
  println(lowerTypeBound(new HatchBackSaloon()))

}

最佳答案

您的示例中的C实现为Car,而不是HatchbackSaloon

看起来像def lowerTypeBound(c: Car): Car的函数可以接受HatchbackSaloon类型的参数,这并不奇怪,对吧?

尝试这样的事情:

val result: HatchBackSaloon = lowerTypeBound(new HatchBackSaloon)

这将不会编译,因为它将需要CHatchbackSaloon,这不是Car的超类。但这将起作用:
val result: MotorVehicle = lowerTypeBound(new HatchbackSaloon)

因为C在这里是MotorVehicle,所以可以使用。

10-07 16:22