我正在试图找出这段代码发生了什么,试图弄清楚是否有我不理解的东西,或者它是编译器错误还是非直观的规范,让我们定义这两个几乎相同的函数:
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
答案 0 :(得分: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