A safer switch? + abbreviation of member names in enum switches

Justin Johansson no at spam.com
Mon Oct 12 06:01:36 PDT 2009


language_fan Wrote:

> Mon, 12 Oct 2009 04:55:07 -0400, Justin Johansson thusly wrote:
> 
> > Would it be possible for the compiler to infer the declared enum type,
> > in this case Color, making for abbreviation of the enum member names in
> > the case clauses [snip]?
> 
> Yes. Java does this.

My question written in haste.
Strike "possible for the compiler to infer the declared enum type" and
replace with "a desirable feature for the compiler to be able to infer the declared enum type".

Naturally it would be possible.

bearophile Wrote:
> That's a special case, with the purpose of shortening code a little. So while writing Color.something isn't handy, it safe and it has no special casing. So I don't like your idea a lot.

Sorry; my feeling is that if it's not necessary to type the extra verbage, why be compelled to do so,
especially in this case when the type of the case targets are tightly bound to the type of the var
in the switch().  There is absolutely no loss of type safety that I can see .. though I'm prepared to
be corrected.

btw. It's been a few months since I've coded in Java but the reason the issue stuck me was that
I had initially typed the shorter version in D out of die-hard (Java) habit and then, upon
complaint, briefly thought, okay Mr D Compiler, since you insist ...

> Related: I have compiled your code with D1 with warnings (-w):
> enum Color {
>     RED,
>     GREEN,
>     BLUE
> }
> 
> void foo(Color color) {
>     switch (color) {
>         case Color.RED:
>             break;
>         case Color.GREEN:
>             break;
>         case Color.BLUE:
>             break;
>     }
> }
> 
> warning - test.d(8): Error: switch statement has no default
> warning - test.d(8): Error: statement is not reachable
> 
> But there's no need for default there because all enum cases are covered. So that warning test has to be improved.

Indeed.

-- Justin Johansson




More information about the Digitalmars-d mailing list