RFR: 8281100: Spurious "variable might not have been initialized" with sealed class switch

Jan Lahoda jlahoda at openjdk.java.net
Wed Feb 9 09:46:32 UTC 2022


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

-------------

Commit messages:
 - 8281100: Spurious "variable might not have been initialized" with sealed class switch

Changes: https://git.openjdk.java.net/jdk/pull/7402/files
 Webrev: https://webrevs.openjdk.java.net/?repo=jdk&pr=7402&range=00
  Issue: https://bugs.openjdk.java.net/browse/JDK-8281100
  Stats: 107 lines in 4 files changed: 90 ins; 3 del; 14 mod
  Patch: https://git.openjdk.java.net/jdk/pull/7402.diff
  Fetch: git fetch https://git.openjdk.java.net/jdk pull/7402/head:pull/7402

PR: https://git.openjdk.java.net/jdk/pull/7402


More information about the compiler-dev mailing list