假设我们有以下定义:
abstract class A
class B extends A
trait Test[T <: A] {
def foo(t: T) = println("I'm Foo")
def bar(t: T) = t match {
case b: B => foo(b)
case _ => println("Bar says: Other")
}
}
Scala 编译器会报错:
<console>:14: error: type mismatch;
found : b.type (with underlying type B)
required: T
case b: B => foo(b)
^
我不明白,这里有什么问题,因为变量b是同一个对象t并且t是类型T?
或者,编译器确实将变量b视为新变量(与 没有关系t)。然后,b是 的子类型A,但不一定是 的子类型T,因为T可以是 的任意子类型A。这是正确的解释吗?