Enum literals, good? bad? what do you think?

Paul Backus snarwin at gmail.com
Thu Jul 22 16:41:30 UTC 2021


On Wednesday, 21 July 2021 at 15:13:36 UTC, Petar Kirov 
[ZombineDev] wrote:
> OTOH, allowing target-typed literals in one place (variable 
> init / assignment) and not in other (function calls) could be 
> regarded as a pointless and artificial design limitation 
> (similar to how struct literals are allowed only for [variable 
> initialization][3]).
> That could be the reason why C#'s language team decided to 
> allow target-typed `new` expressions in both contexts with C# 9:
>
> * 
> https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-9#fit-and-finish-features
> * 
> https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-9.0/target-typed-new
>
> [3]: https://dlang.org/spec/struct#static_struct_init

IMO D's target-typed literals (also called "polysemous literals") 
are also a misfeature. They lead to weird, unintuitive situations 
where seemingly-equivalent code has different behavior; for 
example:

```d
import std.stdio;

void fun(double[] arr) { writeln("double"); }
void fun(T)(T[] arr) { writeln(T.stringof); }

void main()
{
     fun([1, 2, 3]);
     auto arr = [1, 2, 3];
     fun(arr);
}
```

A language with fully-context-aware type inference would infer 
both arrays as `double[]`. A language with 
fully-context-independent type inference would infer both as 
`int[]`.

In D, however, we get the worst of both worlds: type inference is 
*mostly* context-independent (so we have to add type annotations 
even in cases that are unambiguous), but there are a few special 
cases where context is taken into account (so we have to be 
mindful of context when refactoring, since a change in context 
could change the inferred type of an expression).


More information about the Digitalmars-d mailing list