为什么类型匹配来自封闭方法而不是封闭类时,模式匹配的工作方式不同?例如,
trait Base[T]
case class Derived(v: Int) extends Base[Int]
class Test[A] {
def method(arg: Base[A]) = {
arg match {
case Derived(_) => 42
}
}
}
给出错误
constructor cannot be instantiated to expected type;
found : A$A87.this.Derived
required: A$A87.this.Base[A]
case Derived(_) => 42
^
[当A
是方法类型参数时成功编译
class Test {
def method[A](arg: Base[A]) = {
arg match {
case Derived(_) => 42
}
}
}
在后一种情况下,“ A”是自由类型变量,因此可以表示任何类型:
def method[A](arg: Base[A]) = ...
可以用A
的任何兼容类型调用此方法。
在前一种情况下,“ A
”绑定在方法之外,并且编译器无法看到一种方法来保证您的方法在所有情况下都可以使用。