2012-04-08 66 views
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

+2

这是一个匹配器中的错误 - 有很多关于它的故障单,它应该从Scala 2.10.x开始。 – 2012-04-08 05:13:16

+0

你有链接到票证,所以我可以选择你作为答案? – ilcavero 2012-04-08 13:14:47

+1

正如我所说,关于匹配器有很多门票,我真的不特别感兴趣寻找覆盖这个特定情况的门票。 – 2012-04-08 23:52:51

回答

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