Enum literals, good? bad? what do you think?
Ali Çehreli
acehreli at yahoo.com
Tue Jul 20 21:15:19 UTC 2021
On 7/20/21 1:43 PM, claptrap wrote:
> So if you have a function...
>
> void handleError(OtherResult r);
>
> and call it thus...
>
> handleError(OK);
>
> You know it's OtherResult.OK
>
> Isnt that the point of strong typing?
Most of the time yes, but our enums are not that strong. :) The
following compiles and runs with both types.
enum Animal { Jaguar = 100 }
enum Car { Jaguar = 42 }
void foo(int i) {
}
void main() {
foo(Animal.Jaguar);
foo(Car.Jaguar);
}
But the your argument will probably be
foo(Jaguar);
should work as long as there is no conflict.
But then there is name hijacking. What if that last expression worked
and let's say only Car.Jaguar was in scope. What if I imported an
unrelated module that defined this:
int Jaguar = 0;
I would expect foo(Jaguar) to still work with that int without
complaints because I did not specify the enum version. But then my
program works differently. (In other words, I would not expect the
compiler to complain about a name conflict between an module-level name
and an enum-protected name; that's the whole point anyway.)
In any case, I don't have any problem with extra typing and happy with
D's safer enums. I experimented with the with(Enum) helper but don't use
it anymore. Not a big deal. :/
Ali
More information about the Digitalmars-d
mailing list