Scala:参数化中完全限定类名的模式匹配问题

标签 scala pattern-matching

当使用完全限定的类名参数化时,我在模式匹配 Scala 中的对象时遇到了一个小问题。这是基于 Scala 2.9.0.1。有人知道这段代码有什么问题吗?

scala> "foo" match {
 | case y : Seq[Integer] =>
 | case y : Seq[java.lang.Integer] =>
<console>:3: error: ']' expected but '.' found.
   case y : Seq[java.lang.Integer] =>

为什么第一个版本有效,但后者失败?只有在使用完全限定的类名进行参数化时才会出现该问题。

最佳答案

来自 Scala Language Specification , 第 8.1 节模式, : 后面的标识符需要是所谓的类型模式,在第 8.2 节中定义:

Type patterns consist of types, type variables, and wildcards. A type pattern T is of one of the following forms:

...

A parameterized type pattern T [a(1), . . . , a(n)], where the a(i) are type variable patterns or wildcards _. This type pattern matches all values which match T for some arbitrary instantiation of the type variables and wildcards. The bounds or alias type of these type variable are determined as described in (§8.3).

...

A type variable pattern is a simple identifier which starts with a lower case letter. However, the predefined primitive type aliases unit, boolean, byte, short, char, int, long, float, and double are not classified as type variable patterns.



因此,在语法上,您不能在此位置使用完全限定的类作为类型变量模式。但是,您可以使用类型别名,因此:
type JavaInt = java.lang.Integer
List(new java.lang.Integer(5)) match {
    case y: Seq[JavaInt] => 6
    case _ => 7
}

将按预期返回 6。问题在于,正如 Alan Burlison 指出的那样,以下也返回 6:
List("foobar") match {
    case y: Seq[JavaInt] => 6
    case _ => 7
}

因为类型正在被删除。您可以通过运行 REPL 或带有 -unchecked 选项的 scalac 来查看这一点。

关于Scala:参数化中完全限定类名的模式匹配问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7413671/

相关文章:

scala - 定义一个二维列表并在 for 循环中向其 append 列表,scala

Spark 中 Scala 的收集效率低下?

scala - 展平相同类型的嵌套列表

c# - 当单词出现的顺序或次数不重要时,两个字符串之间的最佳匹配?

linux - SED 命令获取第 x 行和第 y 行之间的第 n 个制表符分隔值

java - 匹配字符串的模式

scalacheck 任意隐式和递归生成器

java - 打开窗口/阶段JavaFX时调用代码

string - 从字符串列表中删除字符

c++ - 使用后缀数组和 LCP(-LR) 实现字符串模式匹配