#Returning from every branch of exhaustive switch

1 messages · Page 1 of 1 (latest)

unique moss
#

@vast coral Noticed that this code example does not work

https://javabook.mccue.dev/switch/exhaustiveness

enum Bird {
    TURKEY,
    EAGLE,
    WOODPECKER
}

boolean isScary(Bird bird) {
    switch (bird) {
        case TURKEY -> {
            return true;
        }
        case EAGLE -> {
            return true;
        }
        case WOODPECKER -> {
            return false;
        }
    }
}

despite returning from every branch of what should be an exhaustive switch, Java is not happy. I don't understand why this is or how to explain it properly, but i want to update that section so its not wrong.

pastel dustBOT
#

<@&987246399047479336> please have a look, thanks.

willow vine
#

Well it still wants its return at the end but interesting as to why.

  boolean isScary(Bird bird) {
    return switch (bird) {
      case TURKEY -> true;
      case EAGLE -> true;
      case WOODPECKER -> false;
    };
  }

Seems more correct to yield the value as intended.

#

So maybe some spec issue at odds with early return.

pulsar bone
#

You're not returning in case there's a different enum value

#

And yes, that enum value might change in the future. But they did address that in the newer switch statements

#

Although there's just a hidden default branch that throws an exception now

unique moss
#

yeah thats why it doesn't track for me

#

the hidden default throws

pulsar bone
#

Your enum can change at any point in time

#

which is why it's there

unique moss
#

right, but look at what @willow vine wrote

#

it still doesn't feel right...

#

unless

#

ohhhhh

#

theres no synthetic default

#

with a switch statement

willow vine
#

If you add another element to the enum, say DODO, then you see the 'non-exhaustive' error in my example but original example it's still calling for a return.

unique moss
#

this doesn't feel like a complete explanation though

#

since apparently adding case null -> makes it work

restive sable
#

not really into this chat, but doesnt that make sense?

#

being it null is still possible

unique moss
#

generally switches are null hostile

restive sable
#

ok yea true

unique moss
#

so there's an implicit if (x == null) { throw new NullPointerException(); }

#

unless there is a case null

#

which makes it make less sense