Scala模式匹配保护中断模式匹配穷举?

时间:2016-08-26 16:26:57

标签: scala

为什么在模式匹配中使用Scala中的详尽模式匹配穷举来保护案例?

chris@chris-870Z5E-880Z5E-680Z5E:~/dev/bitcoins-core$ sbt console
[info] Loading project definition from /home/chris/dev/bitcoins-core/project
[info] Set current project to bitcoin-s-core (in build file:/home/chris/dev/bitcoins-core/)
[info] Starting scala interpreter...
[info] 
Welcome to Scala version 2.11.7 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_101).
Type in expressions to have them evaluated.
Type :help for more information.

scala> sealed trait A 
defined trait A

scala> case class B() extends A 
defined class B

scala> case class C() extends A 
defined class C

scala> val b : A = B() 
b: A = B()

scala> b match { case b : B => () }
<console>:15: warning: match may not be exhaustive.
It would fail on the following input: C()
       b match { case b : B => () }
       ^

scala> b match { case b : B if b.isInstanceOf[B] => ()  }

scala> 

注意最后一行没有详尽的警告,我在这里遗漏了什么吗?

2 个答案:

答案 0 :(得分:3)

看起来这是open issue

A comment by Adriaan Moors

  

我理解它令人失望,而且当我们有防守时我们为什么要拯救不是很直观,但我们的关键设计目标不是发出虚假警告,因为这会破坏它们的效用而烦人很多用户。

答案 1 :(得分:0)

在使用isInstanceOf的第二种情况下,编译器无法发出警告,可能是因为它认为用户知道变量b的类型信息。

情景1

scala> b match { case b : B if b.isInstanceOf[B] => ()  }

scala> def f(b: A) = b match { case b : B if b.isInstanceOf[B] => ()  }
f: (b: A)Unit

scala> f(C())
scala.MatchError: C() (of class C)
  at .f(<console>:14)
  ... 33 elided

场景2

scala> val b: A = C()
b: C = C()

scala> b match { case b : B if b.isInstanceOf[B] => ()  }
scala.MatchError: C() (of class C)
  ... 33 elided