Cannot reuse enum member in different enum

HI,

I have a question about defining enum. I noticed that enum member’s name cannot be reused in different enum, example as shown below:

julia> @enum FRUIT apple orange

julia> @enum COLOR red blue yellow orange
ERROR: invalid redefinition of constant orange
Stacktrace:
 [1] top-level scope at none:0

seems that all enum members will be registered as a constant in same scope, so that member cannot be repeated across all enum, is it an expected behaviour?

Actually, I think orange::COLOR and orange::FRUIT should be both valid.

Thanks.

1 Like

Yes, that’s the way enums work.

Generally, x::T and x::S cannot happen unless either T <: S or S <: T.

1 Like

Check out Encapsulating enum access via dot syntax - #4 by quinnj for a workaround (don’t miss the note at the bottom about Julia 1.0).

I rather wish we’d not shipped @enum in its current form in Julia 1.0—it’s really not great. Oh well. Better enum design is on my personal Julia 2.0 list.

4 Likes

I often just create a tiny module containing only the enum, like Encapsulating enum access via dot syntax - #2 by mbauman.

1 Like

The thing is that you want MyEnum.name to be the enum value named name and you want MyEnum to be the type as well. There’s also the tension between using symbols for this kind of thing versus enums. It rather seems that one wants an enum to be a limited kind of Symbol type with automatic domain checking and conversion to and from integer values for C interop.

3 Likes

Feature request: getproperty on enum type to access instances · Issue #31166 · JuliaLang/julia · GitHub talks about overloading getproperty for Type{<:Enum} which is interesting but might have problems since e.g. reflection likely uses getproperty on arbitrary types (similar to the problem of redefining show on your own types).

We came to the conclusion to always use enums when applicable: Style Guide · JuMP