RFR: 8281100: Spurious "variable might not have been initialized" with sealed class switch
Vicente Romero
vromero at openjdk.java.net
Wed Feb 9 23:06:10 UTC 2022
On Wed, 9 Feb 2022 09:40:21 GMT, Jan Lahoda <jlahoda at openjdk.org> wrote:
> Consider:
>
> interface I permits A, B {}
>
> String data;
> I i = ...;
> switch (i) {
> case A a -> data = 0;
> case B b -> data = 0;
> }
> System.err.println(data); //incorrect error here
>
>
> The specification says that `data` is definitely assigned as the `System.err.println`, as the switch covers `I`, but javac will report an error that the variable may not be assigned.
>
> This patch fixes that - the only tricky part is that if there's an error in the switch (like when the switch is expected to be exhaustive, but is not), the current patch will try to suppress the follow-up "variable may not be assigned" errors. As an example:
>
> interface I permits A, B {}
>
> String data;
> I i = ...;
> switch (i) { //error here, not exhaustive
> case A a -> data = 0;
> }
> System.err.println(data); //no error here, due to the preceding exhaustiveness error
this test case is failing for me, I was expecting it to compile:
sealed interface I permits A, B {}
final class A implements I {}
final class B implements I {}
class Test {
void m(I i) {
int data;
switch (i) {
case A a -> data = 0;
case B b -> data = 0;
};
System.err.println(data);
}
}
-------------
PR: https://git.openjdk.java.net/jdk/pull/7402
More information about the compiler-dev
mailing list