我有这个scala代码:
class Creature {
override def toString = "I exist"
}
class Person(val name: String) extends Creature {
override def toString = name
}
class Employee(override val name: String) extends Person(name) {
override def toString = name
}
class Test[T](val x: T = null) {
def upperBound[U <: T](v: U): Test[U] = {
new Test[U](v)
}
def lowerBound[U >: T](v: U): Test[U] = {
new Test[U](v)
}
}
我们可以看到Creature、Person和Employee之间的层级关系:
Creature <- Person <- Employee
在 def 主目录中:
val test = new Test[Person]()
val ub = test.upperBound(new Employee("John Derp")) //#1 ok because Employee is subtype of Person
val lb = test.lowerBound(new Creature()) //#2 ok because Creature is supertype of Person
val ub2 = test.upperBound(new Creature()) //#3 error because Creature is not subtype of Person
val lb2 = test.lowerBound(new Employee("Scala Jo")) //#4 ok? how could? as Employee is not supertype of Person
我能理解的是:
A <: B
定义 A 必须是子类型或等于 B(上限)A >: B
定义 A 必须是超类型或等于 B(下限)
但是#4 发生了什么?为什么没有错误?由于 Employee 不是 Person 的超类型,我希望它不应该符合绑定类型参数[U >: T]
。
谁能解释一下?