cannot reuse enum member in different enum

#1

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.

#2

Yes, that’s the way enums work.

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

1 Like
#3

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

#4

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
#5

I often just create a tiny module containing only the enum, like Encapsulating enum access via dot syntax.

1 Like
#6

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
#7

https://github.com/JuliaLang/julia/issues/31166 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).

#8

We came to the conclusion to always use enums when applicable: http://www.juliaopt.org/JuMP.jl/v0.19.0/style/#@enum-vs.-Symbol-1