DIPX: Enum Literals / Implicit Selector Expression

ryuukk_ ryuukk.dev at gmail.com
Thu Jun 30 15:41:16 UTC 2022


On Thursday, 30 June 2022 at 09:19:15 UTC, bauss wrote:
> On Thursday, 30 June 2022 at 09:08:30 UTC, Ogi wrote:
>> ... But for some reason it’s not the case with enums. ...
>
> ```d
> enum Color { red, orange = 3 }
>
> int orange = 1;
>
> Color color = orange;
> // what is color?
> // or what about
> auto color = orange;
> // What is color?
> // or this:
> auto color = cast(int)orange;
> // What is color?
> ```
>
> Arguably each of these can be defined behavior and can be 
> solved, but what defined behavior is correct depends entirely 
> on what people expect to be true, and that's very different 
> depending on the type of project(s) people work on, what 
> language background they come from etc.
>
> For me the first one will be 1, because I believe a defined 
> value should override an enum value if specified, but this may 
> be different from others.
>
> The second one is the same, the type should be int and not 
> Color.
>
> The third one has the type int as well and will obviously use 
> the int variable named orange in my expectation.
>
> However I can see the argument for other people wanting the 
> first one to be a compiler error because it's ambiguous, or 
> even that you cannot override enum values and thus it will take 
> the value from Color.
>
> All of these behavior are correct and neither is wrong, as it 
> all just depends on how one think about programming in terms of 
> types, values, rules etc.
>
> I don't think D could ever settle on a single rule here that a 
> majority would agree upon.

it's like asnwsering


```D
int resultValue = 42;

int resultValue()
{
      return 5;
}


void main()
{
      writeln(resultValue);

}

```

in case of ambiguity, the compiler already smart enough to give 
an error:


```
onlineapp.d(6): Error: function `onlineapp.resultValue` conflicts 
with variable `onlineapp.resultValue` at onlineapp.d(4)
```

same could be applied for enums


and here clearer example for errors:

```D
enum Color { orange }

int orange = 5;

void main()
{
     auto color = .orange;  <--- it obviously pick 5; it can't 
deduce it is an enum
     Color color = .orange; <--- it obviously pick orange, it 
already expect an enum
     int color =  .orange;  <--- it obviously pick 5, it already 
expect an int
}
```

No need to overthing it, D is typesafe language, it'll work


More information about the Digitalmars-d mailing list