Compiler could be smarter when dealing with exhaustive switch and final variables?
David Alayachew
davidalayachew at gmail.com
Sat Oct 8 07:07:31 UTC 2022
Hello Amber Dev Team,
When if/else statements and final variables combine, the compiler can make
some helpful assertions. Consider the following code.
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 + "");
}
The above code compiles with no errors whatsoever. The compiler is smart
enough to realize that, no matter what, numA and numB will most certainly
be populated by the time we reach the print statements below the if
statements.
However, the compiler does not make the same realization when working with
exhaustive switches. But since the switch statement is exhaustive,
shouldn't the compiler be able to make the same realization here? If
anything, the switch should be capable of all of the above and more,
correct?
private void exhaustiveSwitchWithFinalUninitialized()
{
final int numA;
final int numB;
SomeInterface abc = new First();
switch (abc) //compiler error unless we uncomment the default
{
case First f ->
{
numA = 1;
numB = 0;
}
case Second s ->
{
numA = 0;
numB = 1;
}
/*
default ->
{
numA = 2;
numB = 2;
}
*/
}
System.out.println(numA + "");
System.out.println(numB + "");
}
I would like it if the compiler could make the same realizations it did for
the if statement. I should also add, this seems to apply to all forms of
exhaustive switch except for those with default clauses.
Obviously, this is easy to work around - I could just make a switch
expression for each variable, and then just populate them individually.
Alternatively, I could just put a default clause any time I need that
compiler realization, though I give up some benefits from exhaustive switch
as a result.
Thank you all for your time and help!
David Alayachew
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/amber-dev/attachments/20221008/ce6859a5/attachment-0001.htm>
More information about the amber-dev
mailing list