6

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

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))"uh?",我不明白为什么它List[String]不像以前那样匹配。如果我List[_]在第二个函数上使用它,它能够正确匹配它,这让我认为这是 scalac 中的一个错误。

我正在使用 Scala 2.9.1

4

1 回答 1

1

这是匹配器中的一个错误;)模式匹配器正在(已经?)为 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
于 2012-04-27T21:09:22.483 回答