更好的类型检查在Scala匹配 [英] Better type checking on match in Scala

查看:184
本文介绍了更好的类型检查在Scala匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

scala> class A
defined class A

scala> class B
defined class B

scala> val a: A = new A
a: A = A@551510e8

scala> a match {
     | case _: B => println("unlikely")
     | case _ => println("no match")
     | }
no match



在上面的例子中,编译器不应该告诉我案例永远不能匹配?一个稍微复杂一点的例子最近吸引了我,导致一个不必要的错误,应该由编译器捕获。

In the example above shouldn't the compiler tell me that one of the cases can never match? A slightly more complicated example recently caught me out, leading to what felt like an unnecessary bug that should have been caught by the compiler.

编辑:

只是为了更清楚这个问题。这是不可能在Scala由于某些原因,我看不到? (我可以理解,如果类型是使用泛型和类型擦除导致问题,但这看起来很直接。)如果这不是不可能有合法的原因,这不是在Scala?如果不是什么时候会添加? ;)

Just to be clearer about the question. Is this impossible in Scala for some reason I can't see? (I can understand if the types were using generics and type erasure was causing problems but this looks pretty straight forward.) And if this is not impossible are there legitimate reasons this isn't in Scala? If not when will it be added? ;)

推荐答案

目前,穷举和冗余检查仅对case类构造函数模式进行。原则上,编译器也可以为其他类型的模式执行此操作。但它必须在SLS中指定正确的测试是做什么。这看起来可行,但不重要,给定不同模式类之间的交互。所以,总之,这是Scala的一个领域,将从进一步的贡献中获利。

Currently, exhaustiveness and redundancy checking are only done for case class constructor patterns. In principle, the compiler could do this for some other kinds of patterns, too. But it would have to be specified in the SLS exactly what tests are done. This looks doable but non-trivial, given the interactions between different pattern classes. So, in summary, that's one of the areas in Scala that would profit from further contributions.

这篇关于更好的类型检查在Scala匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆