Scala:参数化中完全限定类名的模式匹配问题
当使用完全限定的类名参数化 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] =>
为什么第一个版本可以工作,而后者却失败了?该问题似乎仅在使用完全限定的类名进行参数化时才会出现。
I have a little problem in pattern matching an object in Scala when it is parameterized with a fully qualified class name. This is based on Scala 2.9.0.1. Anyone knows what's wrong with this code?
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] =>
Why does the first version work, but the latter fail? The problem only seems to occur when a fully qualified classname is used for the parameterization.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
事实上你的第一个例子也不起作用。如果您在 -unchecked 的情况下运行 REPL,您将看到以下错误:
所以您实际上无法执行您想要执行的操作 - 在运行时,List[Integer] 之间没有区别和一个 List[AnythingElse],所以你不能对其进行模式匹配。您也许可以使用清单来执行此操作,请参阅 http://ofps.oreilly .com/titles/9780596155957/ScalasTypeSystem.html#Manifests 和 http://www.scala-blogs.org/2008/10/manifests -reified-types.html
In fact your first example doesn't work either. If you run the REPL with -unchecked, you'll see the following error:
So you can't actually do what you are trying to do - at run-time there's no difference between a List[Integer] and a List[AnythingElse], so you can't pattern-match on it. You might be able to do this with a Manifest, see http://ofps.oreilly.com/titles/9780596155957/ScalasTypeSystem.html#Manifests and http://www.scala-blogs.org/2008/10/manifests-reified-types.html
根据 Scala 语言规范,第 8.1 节模式,: 后面的标识符需要是称为类型模式,在第 8.2 节中定义:
因此,从语法上讲,您不能在此位置使用完全限定的类作为类型变量模式。但是,您可以使用类型别名,因此:
将按预期返回 6。问题在于,正如 Alan Burlison 指出的那样,以下代码也返回 6:
因为类型正在被删除。您可以通过运行 REPL 或带有 -unchecked 选项的 scalac 来查看这一点。
From the Scala Language Specification, section 8.1 Patterns, the identifier after the : needs to be what is referred to as a Type Pattern, defined in Section 8.2:
So, syntactically, you can't use a fully qualified class as a type variable pattern IN THIS POSITION. You can however, use a type alias, so:
will return 6 as expected. The problem is that as Alan Burlison points out, the following also returns 6:
because the type is being erased. You can see this by running the REPL, or scalac with the -unchecked option.