Why does an exhaustive match possibly throw MatchError?

Hello. I have lately taken interest in decompiling the output of Scala compiler (Scala 3.10.0 in my case).

I have always thought that being explicit by specifying None case is better. Two examples to compare:

x match {
  case Some(y) =>
  case None =>
}
x match {
  case Some(y) =>
  case _ =>
}

But first one (the recommended one) produces significantly worse output (java decompiled):

    Option<Integer> option = ...;
    if (option instanceof Some) {
        return ...;
    }
    if (None$.MODULE$.equals(option)) {
        return ...;
    }
    throw new MatchError(option);
}

vs.

    Option<Integer> option = ...;
    if (option instanceof Some) {
        return ...;
    }
    return ...;

The problem is that throw new MatchError(option) makes the option escape, which means JDK cannot scalar-allocate the Option (stack or registers).

Note that this example is just the simplest one with Option, there are way more complex exhaustive patterns. For example, I was pattern matching on (Option[A], Option[B]), and MatchError then makes the Tuple2 escape, and on top of that the Scala optimizer (-opt) was not able to elide the tuple into two vals like it usually can, see example:

(x, y) match {
  case (Some(a), Some(b)) =>
  case (Some(a), None) =>
  case (None, Some(b)) =>
  case (None, None) => // just saying case _ => here avoid tuple allocation by -opt, and does not throw MatchError
}

How do I balance what is better for the code quality and what is better for performance? Is this a bug?

3 Likes

The equals check is specified, and may fail.

I hoped (to no avail) that it would do better with:

case _: None.type =>

I assume the general problem is that the ADT may have been recompiled with an additional case.

This is not an answer, but

case none =>

is idiomatic for “documentation” purposes. Similarly for case nil =>.

Apparently that still warns for -Wunused, but I had an idea not to warn if it names the exhaustive case (when uppercased). Then the lint would “backstop” the idiom. (case Nil @ _ => is tedious to write but would avoid uppercasing.)

2 Likes

Oh yes, thanks, that is in 3.10.1-RC1.