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.