使用序列匹配器混合类型匹配会在Scala中发出奇怪的行为

我试图找出这段代码发生了什么,试图找出是否有我不理解的东西,或者它是编译器错误还是非直观的规范,让我们定义这两个几乎相同的函数:

def typeErause1(a: Any) = a match {
    case x: List[String] => "stringlists"
    case _ => "uh?"
}
def typeErause2(a: Any) = a match {
    case List(_, _) => "2lists"
    case x: List[String] => "stringlists"
    case _ => "uh?"
}

现在,如果我调用typeErause1(List(2,5,6)),我会得到“stringlists”,因为即使它实际上是类型擦除的List [Int],它也无法区分.但奇怪的是,如果我调用typeErause2(List(2,5,6)),我会得到“呃?”我不明白为什么它不像以前那样匹配List [String].如果我在第二个函数上使用List [_],它能够正确匹配它,这让我觉得这是scalac中的一个错误.

我正在使用Scala 2.9.1

最佳答案
这是匹配器中的一个错误;)模式匹配器(已经是?)rewritten为2.10

我刚刚检查了最新的每晚,你的代码按预期工作:

Welcome to Scala version 2.10.0-20120426-131046-b1aaf74775 (Java HotSpot(TM) 64-Bit Server VM, Java 1.6.0_31).
Type in expressions to have them evaluated.
Type :help for more information.

scala> def typeErause1(a: Any) = a match {
     |     case x: List[String] => "stringlists"
     |     case _ => "uh?"
     | }
warning: there were 2 unchecked warnings; re-run with -unchecked for details
typeErause1: (a: Any)String

scala> def typeErause2(a: Any) = a match {
     |     case List(_, _) => "2lists"
     |     case x: List[String] => "stringlists"
     |     case _ => "uh?"
     | }
warning: there were 3 unchecked warnings; re-run with -unchecked for details
typeErause2: (a: Any)String

scala> typeErause1(List(2,5,6))
res0: String = stringlists

scala> typeErause2(List(2,5,6)) 
res1: String = stringlists

转载注明原文:使用序列匹配器混合类型匹配会在Scala中发出奇怪的行为 - 代码日志