2016-01-06 84 views
3

在斯卡拉,爲什麼設置方法類型參數的較低類型邊界不強制方法爭論的「是超類型」限制?斯卡拉更低類型綁定'是方法參數的子類型'限制

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())) 

} 
+0

我想這種回答我的問題[如何Java編譯器爲下界通配符進行類型擦除?](http://stackoverflow.com/questions/25480172/how-does-the-java-compiler-perform型擦除換下界-通配符) – tdmadeeasy

回答

6

C在你的例子是物化爲Car,不HatchbackSaloon

看起來像def lowerTypeBound(c: Car): Car的函數可以接受類型爲HatchbackSaloon的參數,這並不奇怪,對吧?

嘗試這樣:

val result: HatchBackSaloon = lowerTypeBound(new HatchBackSaloon) 

這不會編譯,因爲它需要CHatchbackSaloon,這不是一個Car超。但是,這將工作:

val result: MotorVehicle = lowerTypeBound(new HatchbackSaloon) 

因爲CMotorVehicle這裏,這是允許的。