Case default
Gavin Bierman
gavin.bierman at oracle.com
Tue Jun 15 16:50:10 UTC 2021
Hi
> On 15 Jun 2021, at 15:16, Thiago Henrique Hupner <thihup at gmail.com> wrote:
>
> 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.
It’s in that JEP. It’s a little hidden, but it’s in the section "4b. New label forms arising from null labels”.
> 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.
No. The case default possibility is there because you may want to combine it with the new case null label, e.g.
case null, default -> // matches null and any other value
A case default by itself is allowed (why would we disallow it?) but a default switch label may be more readable.
If you want a pattern variable then you should write a pattern!
Gavin
More information about the amber-dev
mailing list