1

The following code defines an exhaustive match over a Vector, v.

def testExhaustiveness(v: Vector[Int]) = {
  v match {
    case Vector() => println("v is empty")
    case ns :+ n => println("v has at least one element")
  }
}

@main
def main = {
  testExhaustiveness(Vector())     // v is empty
  testExhaustiveness(Vector(1))    // v has at least one element
  testExhaustiveness(Vector(1, 2)) // v has at least one element
}

However, the compiler gives [E029]

18 |  v match {
   |  ^
   |match may not be exhaustive.
   |
   |It would fail on pattern case: Vector(_, _*), Vector(_, _*), Vector(_, _*), Vector(_, _*), Vector(_, _*), Vector(_, _*)
   |
   | longer explanation available when compiling with `-explain`

I imagine this is in error. So, how can I get the compiler to recognise my exhaustive match? I understand we can suppress warnings with a pragma, but is there a destructuring that is accepted by the compiler?

2
  • 1
    You can move the empty case as the last one and do case _ => // empty case. But, note that pattern matching on Vector is kind of a hack, rather than a default operation like on List and in general it would be better if you write your code either using List or other Vector operations. Commented Jul 8 at 13:24
  • 2
    First of all: it's not an error. Compiler can only check exhaustiveness of subtypes of some sealed trait (or components of a sum type). To expand on @LuisMiguelMejíaSuárez comment: Vector is not build like List, with sealed + 2 public case classes. it has several private implementations and things like :+ or +: are objects implementing unapply method. Unfortunately, even if one could build an exhaustive match from a set of values with unapply compiler does not know it, and so it should complain. Commented Jul 8 at 19:38

0

Browse other questions tagged or ask your own question.