On Wednesday, 20 July 2016 at 18:08:14 UTC, stunaep wrote:
On Wednesday, 20 July 2016 at 05:45:21 UTC, Jonathan M Davis wrote:
On Wednesday, July 20, 2016 04:03:23 stunaep via Digitalmars-d-learn wrote:
[...]

If you want the list of members in an enum, then use std.traits.EnumMembers and you'll get a compile-time list of them. It can be made into a runtime list by being put into an array literal.

[...]

Coming from Java I've learned to love enums that are separate objects, that can store multiple values, and that can have methods that can be in their scope. Seems to me like there's no reason to even use enums in D. What's the point when just making a constant would do the same exact thing?

You can easily emulate Java enums in D.

class MyEnumClass
{
    // fields and methods, as a class
    private int val;
    public int foo()
    {
         return val * 2;
    }

    // private ctor: user cannot instantiate the class
    private this(int i)
    {
        val = i;
    }

    // your enumerated instances
    static immutable ONE;
    static immutable TWO;
    static immutable THREE;

    // initialize the enumerate values on program startup
    shared static this()
    {
        ONE = new MyEnumClass(1);
        TWO = new MyEnumClass(2);
        THREE = new MyEnumClass(3);
    }
}

It's not much longer than the equivalent Java code and is way clearer (you know exactly what's going on under the hood).

In java an enum is just an extension of the singleton pattern, where there's a finite set of instantiation instead of exactly one.

A D enum (or a C one, or a C++ one) is a totally different thing.

Reply via email to