javajava-21java-23

Why does pattern matching with switch on InetAddress fail with 'does not cover all possible input values'?


In Java 21 and 23, java.net.InetAddress is declared

public sealed class InetAddress implements Serializable permits Inet4Address, Inet6Address {

However, the following code:

switch (addr) {
     case Inet4Address a -> ...;
     case Inet6Address a -> ...;
};

does not compile with:

the switch expression does not cover all possible input values

Am I missing something, or is this a Java bug?


Solution

  • The code provided is missing a case for InetAddress itself:

    InetAddress foo = null;
    System.out.println(switch (foo) {
      case Inet4Address unused -> "Inet4Address";
      case Inet6Address unused -> "Inet6Address";
      case InetAddress unused -> "InetAddress";
    });
    

    Notice that we want to put InetAddress as last case since it would otherwise make the other two cases unreachable.