当使用完全限定的类名参数化时,我在模式匹配 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/