模式匹配开关是否需要在 Java 中始终详尽无遗?

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

JEP 406 状态:

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 pattern matched switch need to be always exhaustive in java?

答案是肯定的。这在 §14.11.2:

中给出

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

“增强型 switch 语句”的定义在该语句之前不久给出

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.

这意味着带有模式匹配的 switch 始终是增强的 switch 语句。


但是你的问题 body 是一个不同的、非常具体的问题:

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.

这是否意味着无论用作语句还是表达式,模式匹配开关都需要强制穷举?

这个问题的答案是,不,这个引用的句子没有那个意思。这句话的主语是“模式变量”,作用域是“关联的switch规则表达式、switch规则块或switch规则throw语句”。所以它甚至没有远程谈论整个 switch 声明的详尽性。

当你有,例如

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

“模式变量”是p->右边的部分是“关联的开关规则表达式”,引用的句子说在后者中,变量p 是“绝对匹配”:

这对于 §6.3 来说是正式必要的,以确定变量将在范围内并初始化到 -> 的右侧(或者 : 如果您仍在使用它).

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.