ilc*_*ero 6 scala pattern-matching
我试图找出这段代码发生了什么,试图找出是否有我不理解的东西,或者它是编译器错误还是非直观的规范,让我们定义这两个几乎相同的函数:
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?"
}
Run Code Online (Sandbox Code Playgroud)
现在,如果我打电话给typeErause1(List(2,5,6))我,"stringlists"因为即使它实际上是List[Int]类型擦除它也无法区分.但奇怪的是,如果我打电话给typeErause2(List(2,5,6))我"uh?",我不明白为什么它List[String]不像以前那样匹配.如果我List[_]在第二个函数上使用它,它能够正确匹配它,这让我觉得这是scalac中的一个错误.
我正在使用Scala 2.9.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
Run Code Online (Sandbox Code Playgroud)