Compiler could be smarter when dealing with exhaustive switch and final variables?
David Alayachew
davidalayachew at gmail.com
Sat Oct 8 19:35:55 UTC 2022
Terribly sorry Jan, I have been using JDK 18.0.2 this entire time.
For JDK 19, everything works, as you said. However, for JDK 18.0.2, this is
my repeatable example and the corresponding error.
public class TestExhaustivenessBug
{
sealed interface SomeInterface {}
record First() implements SomeInterface {}
record Second() implements SomeInterface {}
private void exhaustiveIfWithFinalUninitialized()
{
SomeInterface abc = new First();
final int numA;
final int numB;
if (abc instanceof First)
{
numA = -1;
numB = -1;
}
else if (abc instanceof Second)
{
numA = -2;
numB = -2;
}
else
{
throw new IllegalStateException("This shouldn't be possible!");
}
System.out.println(numA + "");
System.out.println(numB + "");
}
private void exhaustiveSwitchWithFinalUninitialized()
{
final int numA;
final int numB;
SomeInterface abc = new First();
switch (abc)
{
case First f ->
{
numA = 1;
numB = 0;
}
case Second s ->
{
numA = 0;
numB = 1;
}
}
System.out.println(numA + "");
System.out.println(numB + "");
}
}
And here is the error I received.
TestExhaustivenessBug.java:74: error: variable numA might not have been
initialized
System.out.println(numA + "");
^
TestExhaustivenessBug.java:75: error: variable numB might not have been
initialized
System.out.println(numB + "");
^
Note: TestExhaustivenessBug.java uses preview features of Java SE 18.
Note: Recompile with -Xlint:preview for details.
2 errors
Apologies for the trouble and confusion.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/amber-dev/attachments/20221008/a612274b/attachment.htm>
More information about the amber-dev
mailing list