Case default

Thiago Henrique Hupner thihup at gmail.com
Tue Jun 15 14:16:07 UTC 2021


Hi.

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.

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.


More information about the amber-dev mailing list