我有这个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 main中:
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]
。
任何人都可以解释?
答案 0 :(得分:2)
这个例子可能有帮助
scala> test.lowerBound(new Employee("Scala Jo"))
res9: Test[Person] = Test@1ba319a7
scala> test.lowerBound[Employee](new Employee("Scala Jo"))
<console>:21: error: type arguments [Employee] do not conform to method lowerBound's type parameter bounds [U >: Person]
test.lowerBound[Employee](new Employee("Scala Jo"))
^
一般情况下,它连接到Liskov Substitution Principle - 您可以在任何地方使用子类型而不是超类型(或者#34;子类型总是可以转换为其超类型&#34;),因此类型推断试图推断尽可能最近的超类型(如Person
这里)。
因此,对于ub2,[Nothing..Person]
和[Creature..Any]
之间没有这样的交集,但对于lb2,[Person..Any]
和[Employee..Any]
之间存在一个交叉点 - 那就是&#39} Person
。因此,您应明确指定类型(强制Employee
而不是[Employee..Any]
)以避免此处的类型推断。
即使使用类型推断,lb2预期会失败的示例:
scala> def aaa[T, A >: T](a: A)(t: T, a2: A) = t
aaa: [T, A >: T](a: A)(t: T, a2: A)T
scala> aaa(new Employee(""))(new Person(""), new Employee(""))
<console>:19: error: type arguments [Person,Employee] do not conform to method aaa's type parameter bounds [T,A >: T]
aaa(new Employee(""))(new Person(""), new Employee(""))
^
此处类型A
在第一个参数列表中被推断并固定为Employee
,因此第二个参数列表(抛出错误)只有选择 - 按原样使用它。
最常用的示例包含不变O[T]
:
scala> case class O[T](a: T)
defined class O
scala> def aaa[T, A >: T](t: T, a2: O[A]) = t
aaa: [T, A >: T](t: T, a2: O[A])T
scala> aaa(new Person(""), O(new Employee("")))
<console>:21: error: type mismatch;
found : O[Employee]
required: O[Person]
Note: Employee <: Person, but class O is invariant in type T.
You may wish to define T as +T instead. (SLS 4.5)
aaa(new Person(""), O(new Employee("")))
^
此处{p> T
已固定为Employee
,无法将O[Employee]
转换为O[Person]
{{1}}由于默认情况下的不变性。
答案 1 :(得分:1)
我认为这是因为您可以将任何Person
传递给您的
Test[Person].lowerBound(Person)
由于Employee
是Person
的子类,因此它被视为合法Person
。