上界类型与正常类行为的差异

我正在Scala中学习泛型,但我无法理解“正常”类层次结构和上界类型之间的区别。

看下面的示例:笼子可以收到Animal类,这意味着我可以通过Animal类或Dog类。上限参数同样有效。它们之间的实际区别是什么?什么时候应该使用其中一个?

class Animal
class Dog extends Animal

class Cage(animal: Animal)
val cage = new Cage(new Dog)

class AnotherCage[A <: Animal](animal: A)
val anotherCage = new AnotherCage(new Dog)
评论
  • 对你的冷漠
    对你的冷漠 回复

    One difference is in the static type of animal parameter where in the former case it is typed as Animal whilst in latter case it is typed as Dog because the type parameter A is substituted with concrete type Dog . To see the difference try adding a sound method to Dog like so

    class Animal
    class Dog extends Animal {
      def sound = "woof"
    }
    
    class Cage(val animal: Animal)
    val cage = new Cage(new Dog)
    
    class AnotherCage[A <: Animal](val animal: A)
    val anotherCage = new AnotherCage(new Dog)
    
    cage.animal.sound         // error
    anotherCage.animal.sound  // ok
    

    Note how compiler is not aware of sound method in the first case despite the fact that the runtime class referenced by animal argument is Dog.