Classes as enums in D?
Rikki Cattermole via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sun Nov 29 23:54:46 PST 2015
On 30/11/15 8:48 PM, Andrew LaChance wrote:
> 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.
enums don't have to be integral, but for performance reasons it is for
the best.
enum Foo : string {
A = "a",
B = "b",
C = "d",
ERROR = "What are you talking about?"
}
void main() {
import std.stdio : writeln;
Foo foo = Foo.ERROR;
writeln(foo, " is: ", cast(string)foo);
}
Also you are welcome in #d on Freenode (IRC) if you are interesting in
talking with the rest of us!
Btw you probably want tuples (std.typecons : tuple) to emulate those values.
More information about the Digitalmars-d-learn
mailing list