gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 04:44:12 25 4
gpt4 key购买 nike

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com