RFR: 8281100: Spurious "variable might not have been initialized" with sealed class switch
Vicente Romero
vromero at openjdk.java.net
Thu Feb 10 17:12:09 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
yep I also can't reproduce the issue, redid everything, I did yesterday, probably some build issue, not sure because I cleaned and rebuilt several times yesterday to be sure, anyway, yes it is working fine for me too now, sorry for the noise,
> > 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);
> > }
> > }
> > ```
>
> Hm, seems to work for me with this patch?
>
> ```
> ~/src/jdk/jdk (JDK-8281100) $ cat /tmp/Test.java
> 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);
> }
> }
> ~/src/jdk/jdk (JDK-8281100) $ ./build/linux-x86_64-server-release/jdk/bin/javac --enable-preview -source 19 /tmp/Test.java
> Note: /tmp/Test.java uses preview features of Java SE 19.
> Note: Recompile with -Xlint:preview for details.
> ~/src/jdk/jdk (JDK-8281100) $ git push origin JDK-8281100
> Everything up-to-date
> ```
-------------
PR: https://git.openjdk.java.net/jdk/pull/7402
More information about the compiler-dev
mailing list