Scala 上界和下界的混淆

Scala 上界和下界的混淆,scala,Scala,我希望测试新孙子会给出编译错误。它是如何工作的?我是否错误地理解了类型绑定?由于孙子扩展了子对象,编译器在调用中选择了B类型参数作为子对象 */ class Parent class Child extends Parent class GrandChild extends Child object main{ def test[B >: Child](x : B) = x; // B should be of type Child or Parent def mai

我希望测试新孙子会给出编译错误。它是如何工作的?我是否错误地理解了类型绑定?

由于孙子扩展了子对象,编译器在调用中选择了B类型参数作为子对象

 */
class Parent 

class Child extends Parent

class GrandChild extends Child

object main{

  def test[B >: Child](x : B) = x; // B should be of type Child or Parent

  def main(args: Array[String]): Unit = {
    test(new Parent); //works. B == Parent
    test(new Child); //works. B == Child
    test (new GrandChild) // works!!! Surprise!!! B == GrandParent. This should not work, right?

  }
}
如果显式指定类型,则会出现预期错误:

test(new GrandChild)

B>:Child意味着B应该是子的超类型,所有这些类都是父-子类和孙子类,因为它们都是从父类扩展而来的。

如果B>:Child意味着B应该是子的超类型,那么测试新孙子类应该失败,因为孙子类不是子的超类型。这应该是一个编译错误,新的子对象和新的孙子对象是父对象的实例,在这里向上转换到父对象
test[GrandChild](new GrandChild)