在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())) }
Dima.. 6
C
在您的示例中,实现为Car
,而不是HatchbackSaloon
.
一个函数看起来def lowerTypeBound(c: Car): Car
可以接受类型的参数HatchbackSaloon
,这并不奇怪,对吧?
尝试这样的事情:
val result: HatchBackSaloon = lowerTypeBound(new HatchBackSaloon)
这将无法编译,因为它需要C
是HatchbackSaloon
,这不是一个超类Car
.但这会奏效:
val result: MotorVehicle = lowerTypeBound(new HatchbackSaloon)
因为C
在MotorVehicle
这里,这是允许的.
C
在您的示例中,实现为Car
,而不是HatchbackSaloon
.
一个函数看起来def lowerTypeBound(c: Car): Car
可以接受类型的参数HatchbackSaloon
,这并不奇怪,对吧?
尝试这样的事情:
val result: HatchBackSaloon = lowerTypeBound(new HatchBackSaloon)
这将无法编译,因为它需要C
是HatchbackSaloon
,这不是一个超类Car
.但这会奏效:
val result: MotorVehicle = lowerTypeBound(new HatchbackSaloon)
因为C
在MotorVehicle
这里,这是允许的.