Does pattern matched switch need to be always exhaustive in Java?

525 views Asked by At

JEP 406 states:

A pattern variable introduced by a switch label is definitely matched in the associated switch rule expression, switch rule block or switch rule throw statement.

Does this mean pattern matched switch needs to be compulsorily exhaustive regardless of whether it's used as a statement or an expression?

1

There are 1 answers

2
Holger On BEST ANSWER

You have asked two different questions. Your question’s title asks

Does pattern matched switch need to be always exhaustive in java?

The answer is yes. This is given in §14.11.2:

If the switch statement is an enhanced switch statement, then it must be exhaustive.

The definition of “enhanced switch statement” is given shortly before that statement

An enhanced switch statement is one where either (i) the type of the selector expression is not char, byte, short, int, Character, Byte, Short, Integer, String, or an enum type, or (ii) at least one of the switch labels has a pattern case label element or a null case label element.

which implies that switch with pattern matching is always an enhanced switch statement.


But the body of your question is a different, very specific question:

A pattern variable introduced by a switch label is definitely matched in the associated
switch rule expression, switch rule block or switch rule throw statement.

Does this mean pattern matched switch needs to be compulsorily exhaustive regardless of whether it's used as a statement or an expression?

The answer to this question is, no, this cited sentence does not have that meaning. The subject of this sentence is “pattern variable” and its scope is “the associated switch rule expression, switch rule block or switch rule throw statement”. So it’s not even remotely talking about the exhaustiveness of the entire switch statement.

When you have, e.g.

   case Point p && p.x > 20 -> System.out.println("the right " + p);

The “pattern variable” is p and the part to the right of the -> is “the associated switch rule expression” and the cited sentence says that within the latter, the variable p is “definitely matched”:

This is formally necessary for §6.3 to establish that the variable will be in scope and initialized to the right of the -> (or : if you’re still using it).

The scope of a pattern variable declaration (that is, a local variable declared by a pattern) is the part of the program that might be executed after the matching of a value against the pattern has succeeded (§14.30.2). It is determined by considering the program points where the pattern variable is definitely matched in a region beginning with the pattern that declares the pattern variable.