Unable to use “case null” in a switch statement

This may be expected, but it caught me out:

main() {
  String a;
  switch(a) {
    case "a":
    case null:

It gives the error:

Case expressions must have the same types, ‘null’ isn’t a ‘String’.

It seems strange that it says null is not a String, when it’s the actual value assigned to the String variable.

Author: Fantashit

1 thought on “Unable to use “case null” in a switch statement

  1. This is a known consequence of the way the specification is written. The specification requires all case expressions to be instances of the same class, and null is an instance of Null, not String.

    Maybe we can begin to loosen up a little, say, to all expressions just needing to be subtypes of the static type of the case expression, now that we have a non-optional type system.

Comments are closed.