Classes as enums in D?

Andrew LaChance via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Nov 29 23:48:35 PST 2015


Hello,
D has intrigued me for a while, and I thought I would finally 
read up on it!  I've been reading "Programming in D" by Ali 
Çehreli and I've been thinking about how I can use the language 
in a side project I'm working on, porting it from java to D.  One 
of the uncommonly-used features of java that I like is how enums 
can be full classes (though I don't like that there's no option 
to use enums as e.g. regular ints).  This allows several 
benefits, such as the ability to use them in switch statements 
like regular enums, the full set of objects is known at compile 
time, all objects are immutable, it's impossible to accidentally 
or purposefully create new objects of that type, etc...

For example (in java), if I wanted to have an enum that describes 
all the white keys on a piano keyboard and have members that 
describe the number of half-steps to the next white key and to 
the previous white key, I can define an enum (the "id" or enum 
value is implicitly defined so it doesn't have to be explicitly 
written in the definition):

enum WhiteKey
{
     A(2,2),
     B(2,1),
     C(1,2),
     D(2,2),
     E(2,1),
     F(1,2),
     G(2,2);

     private final int halfStepsToNext;
     private final int halfStepsToPrevious;

     WhiteKey(int halfStepsPrevious, int halfStepsNext)
     {
         this.halfStepsToPrevious = halfStepsPrevious;
         this.halfStepsToNext = halfStepsNext;
     }
}

 From what I've read and seen, in D all enums have forced to 
integral types.  Is it possible to do the above in D and I have 
just missed it?  I can think of a few ways around it (such as 
statically create and define a bunch of WhiteKey structs, ...), 
but none are as clean as the above.  If this isn't something 
supported, is it on a roadmap of wanted features?

Thanks!  I'm looking forward to really getting to know the 
language.


More information about the Digitalmars-d-learn mailing list