scala下界应该允许相同的层次结构对象?

我刚刚开始使用
Scala,想要清除一些基础知识.在下面的函数中,下限设置为Puppy.为什么Puppy1和Puppy2在下面的代码中是允许的.

class Animal
class Dog extends Animal
class Puppy extends Animal
class Puppy1 extends Animal
class Puppy2 extends Puppy

class AnimalCarer{
    def display [T >: Puppy](t: T){
    println(t)
    }
}

val animal = new Animal
val dog = new Dog
val puppy = new Puppy
val puppy1 = new Puppy1
val puppy2 = new Puppy2

val animalCarer = new AnimalCarer
animalCarer.display(animal)
animalCarer.display(puppy)
animalCarer.display(puppy1)
animalCarer.display(puppy2)
animalCarer.display(dog)

最佳答案 这是Scala类型推断的典型例子,它与常见的概念(直觉)相混淆.

def foo[T >: Puppy](t: T) = t

foo(new Puppy1) //compiles

foo[Puppy1](new Puppy1) //give compilation error

Scala REPL

scala> def foo[T >: Puppy](t: T) = t
foo: [T >: Puppy](t: T)T

scala> foo(new Puppy1)
res9: Animal = Puppy1@4d49af10

scala> foo[Puppy1](new Puppy1)
<console>:16: error: type arguments [Puppy1] do not conform to method foo's type parameter bounds [T >: Puppy]
       foo[Puppy1](new Puppy1)
      ^
点赞