Switch on null

Remi Forax forax at univ-mlv.fr
Sat Apr 30 10:10:33 UTC 2022


----- Original Message -----
> From: "Nathan Reynolds" <numeralnathan at gmail.com>
> To: "amber-dev" <amber-dev at openjdk.java.net>
> Sent: Saturday, April 30, 2022 4:47:36 AM
> Subject: Switch on null

> I realize I am late to the discourse.  I discovered that JavaScript allows
> for...
> 
> switch (value)
> {
>   case null: ...
> }
> 
> What are the problems with allowing such a thing in Java?

Hi Nathan,

You can do that since Java 17, as a preview feature.
With more recent releases, you can even have a case that say null or String 

Object o = ...
switch(o) {
  case null, String s -> System.out.println("string or null");
  default -> System.out.println("default");
}

As a fun tidbit, by default in order to be backward compatible a switch statement on an enum is not required to be exhaustive. If you want to ask the compiler to verify that the switch is exhaustive you can add "case null -> throw null".

enum Color { RED, BLACK }

// this one compile, the switch is not required to be exhaustive by backward compatibility
switch(color) {
  case RED -> ...
}

// this one does not compile, the switch is required to be exhaustive
switch(color) {
  case null -> throw null;
  case RED -> ...
}

// and obviously, this one compiles
switch(color) {
  case null -> throw null;
  case RED -> ...
  case BLACK -> ...
}


regards,
Rémi


More information about the amber-dev mailing list