因此,scala编译器抱怨方式foo
的模式匹配可能并不完整,我不知道为什么。这是代码:匹配的部分可能并不完整无误警告不正确
abstract class Foo {
def foo(that: Foo): Unit = (this, that) match {
case (Foo_1(), Foo_1()) => //case 1
case (Foo_1(), Foo_2()) => //case 2
case (Foo_2(), Foo_1()) => //case 3
case (Foo_2(), Foo_2()) => //case 4
// Compiler warning
}
def fooThis(): Unit = this match {
case Foo_1() => //do something
case Foo_2() => //do something
// Works fine
}
def fooThat(that: Foo): Unit = that match {
case Foo_1() => //do something
case Foo_2() => //do something
// Works fine
}
}
case class Foo_1() extends Foo
case class Foo_2() extends Foo
这是错误:
Warning:(5, 32) match may not be exhaustive.
It would fail on the following inputs: (Foo(), _), (Foo_1(), _), (Foo_2(), _), (_, Foo()), (_, Foo_1()), (_, Foo_2()), (_, _)
def foo(that: Foo): Unit = (this, that) match {
由于this
和that
是Foo
类型,Foo
只能是Foo_1
类型或Foo_2
的,在foo
的案件所有可能的组合。
为了完整起见,我添加了fooThis
和fooThat
,并表明匹配Foo_1
和Foo_2
就足够了。编译器消息表明还有其他类型可以匹配(即Foo
和_
)。
那么为什么会显示此警告?
相关:
- Scala bug: fixed in 2.12.0-M4。我的斯卡拉欢迎消息:
Welcome to Scala 2.12.1 (Java HotSpot(TM) Client VM, Java 1.8.0_131).
- Scala bug: false match not exhaustive warning on (unsealed, sealed) tuple
编辑
编译器似乎只要你使用的元组抱怨。如果我们添加一个虚拟变量来fooThis
如下
def fooThis(): Unit = (this, Foo_1()) match {
case (Foo_1(),_) => //do something
case (Foo_2(),_) => //do something
}
我们得到以下编译器警告
Warning:(13, 27) match may not be exhaustive.
It would fail on the following input: (_, _)
def fooThis(): Unit = (this, Foo_1()) match {
我确实可能会问我的问题是错的,我宁愿问你最后一段的问题。我错过了什么,或者你没有在这个答案中自己回答吗?对我来说,这种不一致困扰着我,而不是编译器产生警告。 – Didii
你是对的,不一致是震动。 (不满意的)答案最终是Scala编译器不会为未密封的特征生成穷举警告。你并不是唯一想要的,正如Typelevel的fork中的'strict-unsealed-patmat'编译器选项所证明的那样。也许我们会在未来的某个Lightbend斯卡拉的版本得到严格'开封-patmat'。在此期间我猜只是意识到这一点,并坚持对抽象数据类型匹配。 – danielnixon