Home > Software design >  Java 17 null case with pattern matching
Java 17 null case with pattern matching

Time:06-13

I have a Java 17 project using Eclipse 2022-03 and OpenJDK 17:

openjdk 17.0.2 2022-01-18
OpenJDK Runtime Environment Temurin-17.0.2 8 (build 17.0.2 8)
OpenJDK 64-Bit Server VM Temurin-17.0.2 8 (build 17.0.2 8, mixed mode, sharing)

I'm trying to use the new Java 17 switch features, so I tried this in a method:

return switch(testEnum) {
  case foo -> newFoo();
  case bar -> newBar();
}

That works fine. But then I tried this (because the value might be null):

return switch(testEnum) {
  case foo -> newFoo();
  case bar -> newBar();
  case null -> newDefault();
}

Eclipse underlines null in red and says:

Pattern Matching in Switch is a preview feature and disabled by default. Use --enable-preview to enable

Compiling via Maven produces:

[ERROR] /project/src/main/java/com/example/FooBar.java:[432,38] null in switch cases is a preview feature and is disabled by default.
[ERROR]   (use --enable-preview to enable null in switch cases)

My Maven project has:

<properties>
  <maven.compiler.release>17</maven.compiler.release>
</properties>

I know the compiler release setting isn't being ignored; otherwise it would be defaulting to Java 8 (as per my parent POM) and not allowing pattern matching at all.

Isn't null cases with pattern matching part of Java 17? What am I doing wrong?

CodePudding user response:

tl;dr

  • Related