Case default

Brian Goetz brian.goetz at oracle.com
Tue Jun 15 15:04:53 UTC 2021


> Trying out the JEP 406: Pattern Matching for switch and I've found that the
> compiler
> is accepting "case default" instead of only "default".
> However, I couldn't find which JEP added this support.

This is part of "Pattern Matching for Switch" (JEP 406), a preview 
feature in 17.  This is one of the regularizations of switch that is 
needed as switch labels become more powerful.

> Another thing that came up when migrating some existing code to pattern
> matching for switch
> was the ability to "match" a default value. An example of what I tried to
> do was changing
> this:
>
> private static Long coerceToLong(Object value) {
>          value = convertToNumber(value);
>          if (value instanceof Long newValue) {
>              return newValue;
>          }
>          if (value instanceof Number number) {
>              return number.longValue();
>          }
>          if (value instanceof String newValue) {
>              return Long.valueOf(newValue);
>          }
>          throw new Exception(CANNOT_CONVERT_TO.formatted(value, "Long"));
>      }
>
> To this:
>
> private static Long coerceToLong(Object value) {
>          return switch(convertToNumber(value)) {
>              case Long asLong -> asLong;
>              case Number asNumber -> asNumber.longValue();
>              case String asString -> Long.valueOf(asString);
>              case default asValue -> throw new
> Exception(CANNOT_CONVERT_TO.formatted(asValue, "Long"));
>          };
>      }
>
> However, as the default case doesn't allow a pattern variable, I had to do
> the following
>
>      private static Long coerceToLong(Object value) {
>          value = convertToNumber(value);
>          return switch(value) {
>              case Long asLong -> asLong;
>              case Number asNumber -> asNumber.longValue();
>              case String asString -> Long.valueOf(asString);
>              case default -> throw new
> ELException(CANNOT_CONVERT_TO.formatted(value, "Long"));
>          };
>      }
>
> This is OK, but as long as the switch allows "case default", it gives the
> impression that
> the value is available to extract too.

You can use a more expansive pattern, such as `case Object o`, to bind 
to the value.




More information about the amber-dev mailing list