Final variable initialization problem with exhaustive switch
Remi Forax
forax at univ-mlv.fr
Wed Jan 12 22:21:15 UTC 2022
----- Original Message -----
> From: "Mateusz Romanowski" <romanowski.mateusz at gmail.com>
> To: "Dimitris Paltatzidis" <dcrystalmails at gmail.com>
> Cc: "amber-dev" <amber-dev at openjdk.java.net>
> Sent: Wednesday, January 12, 2022 10:22:42 PM
> Subject: Re: Final variable initialization problem with exhaustive switch
> Hi Dimitris et al.,
> I believe there is confusion on whether we are talking about switch
> statement or switch expression.
>
> If I assign value of this `switch` to a variable, it compiles:
> ```
> final int a;
> Object ignored = switch (p) {
> case ODD -> a = 1;
> case EVEN -> a = 0;
> };
> int b = a + 1;
> ```
>
> Otherwise, "error: variable a might not have been initialized" is shown.
yes, Mateusz is right,
with a switch expression the compiler insert a default that throw an exception, while with a switch statement, the old switch, the compiler insert a default that does nothing.
This code compiles because it's a switch expression
final int a;
Object ignored = switch (p) {
case ODD -> a = 1;
case EVEN -> a = 0;
// the compiler adds a default that throws an exception
};
and this code compiles because it's a switch statement with a default
final int a;
switch (p) {
case ODD -> a = 1;
case EVEN -> a = 0;
default -> throw null;
}
We (the expert group) have discussed about adding a warning for the switch statement asking for a default case but it has no been implemented.
>
> Cheers,
> Mateusz
regards,
Rémi
>
>
> On Wed, Jan 12, 2022 at 10:19 PM Pedro Lamarão <pedro.lamarao at prodist.com.br>
> wrote:
>
>> This is what I got:
>>
>> PS E:\> E:\opt\jdk-17+35\bin\java --version
>> openjdk 17 2021-09-14
>> OpenJDK Runtime Environment Temurin-17+35 (build 17+35)
>> OpenJDK 64-Bit Server VM Temurin-17+35 (build 17+35, mixed mode, sharing)
>> PS E:\> E:\opt\jdk-17+35\bin\javac --release 17 --enable-preview Main.java
>> Main.java:11: error: variable a might not have been initialized
>> int b = a + 1;
>> ^
>> 1 error
>>
>> Regards,
>> Pedro.
More information about the amber-dev
mailing list