Methods in enums

user1234 user1234 at 12.de
Fri Aug 18 11:21:57 UTC 2023


On Monday, 14 August 2023 at 23:40:33 UTC, WebFreak001 wrote:
> We have UFCS in D, which allows us to define global methods 
> that just take for example an enum as first argument, and then 
> call that global method using syntax 
> `enumArg.globalMethod(rest)` instead of `globalMethod(enumArg, 
> rest)`. I think this is very useful for lots of scenarios.
>
> However enums themselves can't contain any methods. I think for 
> consistency with the other types, such as union, struct, 
> interface, class, etc. it would be nice if enums could just 
> contain member methods, similarly to how structs and unions 
> work. You can't put any methods inside C structs, but D allows 
> it, so why not also for enums?
>
> This would allow selective imports for enums, e.g. `import 
> somemod : MyEnum;` to also pull in all the global UFCS 
> functions. Nowadays IDEs partially make this obsolete, 
> especially if you already know the names of the "member 
> methods" you can call on the enum, since they would auto-import 
> this for you. But I think D's design allowing a lot of code 
> writing without IDE would fit this feature very well, while 
> also benefiting IDE users for automatically having all built-in 
> custom enum functions available to aid discovery, especially of 
> new libraries. Additionally static string parsing methods would 
> naturally fit in there and also allow defining special methods 
> such as toString or other special things that code such as 
> std.conv uses.
>
> Is there possibly a major reason why enums couldn't contain 
> methods? What are your thoughts?
>
> They would of course need a bit of new syntax, like possibly 
> separating the enum values and methods with `;`, like what Java 
> does, or having a more D-like syntax that just allows methods 
> anywhere in the enum. I think the concept itself would fit into 
> the language design very nicely.

you can do that with a mixin declaration + heavy introspection 
code, something like

```
mixin(generateSelectiveImportForTypeAndUFCSCapableFunctionOf!("someModule", "someType")())
```

However one thing I have observed, in the past, is that even if 
you make the metaprog-equivalent code of a compiler-grade 
feature, people wont use it. So at some point the question is 
more: should this be builtin (e.g as a __traits) or be in 
std.typecons/std.traits ?

Big question.


More information about the Digitalmars-d mailing list