Better type checking on match in Scala
The compiler does warn you (in fact compilation fails) if you use case classes:
scala> case class A()
defined class A
scala> case class B()
defined class B
scala> val a = A()
a: A = A()
scala> a match {
| case A() => println("A")
| case B() => println("B")
| case _ => println("_")
| }
<console>:13: error: constructor cannot be instantiated to expected type;
found : B
required: A
case B() => println("B")
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.
I checked in Scala 2.13.3
, we get a warning of fruitless type test
:
scala> a match {
| case _:B => println("B")
| case _ => println("no match")
| }
case _:B => println("B")
^
On line 2: warning: fruitless type test: a value of type A cannot also be a B
no match