有人能告诉我 Java 17 接受最终表达式作为 switch-case-constructs 中的 case 表达式但不接受将最终表达式作为参数传递的好处吗?
void test(int distinction, final int foo) {
final var bar = 2;
switch (distinction) {
case foo -> doSomething(); // does not compile -> case expressions must be constant expressions
case bar -> doSomething(); // does compile
case 3 -> doOtherThings(); // does compile
}
}
为什么编译器不接受情况 1,尽管 foo 和 bar 一样是最终变量?
在我看来,案例 3 的可读性比案例 2 好得多。所以我看不到新语言结构的好处。
最佳答案
案例标签必须是编译时常量。最终参数不是编译时常量;它可能不会在给定的方法调用中发生变化,但它可以在方法的调用中发生变化。 (最终实例字段和没有初始化器的静态最终字段也不是编译时常量。)
关于java - 在 Java 17 switch-case 中使用 final 变量的好处,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70318173/