Search code examples
julia

Symbol enum in Julia?


I would like to avoid using ugly prefixed enum names like direction_right, wonder if it's possible to use symbolic enum names?

The problem, code below won't work because of enum conflict names

@enum Align top right bottom left
@enum Direction up right down left

function play(d::Direction)
  print(d)
end

play(right)

Could something like that be used instead?

@enum Align :top :right :bottom :left
@enum Direction :up :right :down :left

function play(d::Direction)
  print(d)
end

play(:right)

I would like to have type safety, and specify Direction type for argument of play.


Solution

  • You could use Symbols combined with Val and hence be able to dispatch on type (or on value too if needed)

    const Direction = Union{[Val{d} for d in [:up, :right, :down, :left]]...}
    function direct(d::Direction)
       println(typeof{d})
    end
    direct(s::Symbol)=direct(Val{s}())
    

    Now you can do:

    julia> direct(:up)
    Val{:up}
    
    julia> direct(:up1)
    ERROR: MethodError: no method matching direct(::Val{:up1})