The coincidence cannot be exhaustive. The warning is incorrect.

So, the scala compiler complains that pattern matching may not be complete for the method foo, and I wonder why. This is the code:

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

And this is a mistake:

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 {

Because thisand thathave a type foo, and foocan only be of a type Foo_1or Foo_2, in cases foo- all possible combinations.

I added fooThis, and fooThatfor completeness and showed that the coincidence Foo_1and Foo_2enough. A compiler post suggests that there are other types that can be matched (i.e., fooand _).

So why is this warning shown?

on this topic:


, , , . 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 {
+4
3

Scala (, Foo). , fooThis fooThat .

( , , MatchError ), :

  • Foo . ADT, , , . Option - ADT, , , . Foo_1, Foo_2, . - , . , Foo_1 Foo_2 final, .
  • Foo , Typelevel Scala -Xlint:strict-unsealed-patmat.

, Scala , Tuple2, Foo.

" ?", , , :

case class Foo3() extends Foo
val foo3 = Foo3()
foo3.foo(foo3)

(: MatchError .)

- Scala, . , , :

  • Foo (-, ADT), Foo3 .
  • case _ => ....
  • : ((this, that): @unchecked) match { ....

3, MatchError , - Foo3.

, , " Foo ", " fooThis fooThat ".

+4

, :

sealed abstract class Foo {

, . : https://issues.scala-lang.org/browse/SI-9351

+1

, CHA .

, Scala , , , . ( , - , !) , , . , .

0
source

Source: https://habr.com/ru/post/1679392/


All Articles