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

标签 java switch-statement java-17 jep

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 语句。


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

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规则 block 或switch规则抛出语句”。因此,它甚至没有远程谈论整个 switch 语句的详尽性。

当你有,例如<​​/p>

   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.

关于java - 模式匹配开关是否需要在 Java 中始终详尽无遗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69419207/

相关文章:

objective-c - 在 objective-c 的 Switch/Case 语句中对 case 进行分组

c++ - 在无法访问的语句中创建变量是否是明确定义的行为?

spring-boot - Yaml 属性未在 spring boot 中加载

java - 为什么 RecordComponent 没有在 Java 17 的 Records 类中定义的注释信息?

java - java 中的动态 Json 到 CSV。寻找适用于任何 json 的通用代码,无论 json 文件中的节点数量是多少

java - 用户更改后如何获取 Jtable 的列宽

java - 将 switch 与子类一起使用?

java - Java 中的泛型无效

java - 是 Thread.sleep(1000);有什么可靠的东西可以使用吗?

java - 在 RESTEasy Web 服务器上缓存数据?