# Dispatch on enum

**URL:** <https://discourse.julialang.org/t/dispatch-on-enum/77398>\
**Category:** General Usage\
**Tags:** multidispatch, enum\
**Created:** [March 4, 2022, 12:53pm UTC](https://discourse.julialang.org/t/dispatch-on-enum/77398 "2022-03-04T12:53:22Z")\
**Posts on this page:** 1\
**Showing post:** 7

<div class="post-metadata">

**Author:** ![jw3126](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jw3126/32/3086_2.png) [@jw3126](https://discourse.julialang.org/u/jw3126)\
**Post date:** [March 4, 2022, 5:06pm UTC](https://discourse.julialang.org/t/dispatch-on-enum/77398/7 "2022-03-04T17:06:17Z")

</div>

IMO the key strength of multiple dispatch is **not** neat syntax like

```julia
f(::a) = ...
f(::b) = ...
f(::c) = ...

```

This syntax is nice to have but not essential to me.  
Instead the super power of multiple dispatch is openness.  
You can extend `YourLib.f(::MyType) ...` anywhere. This openness enables  
exceptional code reuse in julia, see also [this talk](https://www.youtube.com/watch?v=kc9HwsxE1OY).  
Now in case of enums, all instances are fixed, when the enum is defined.  
So there is no openness benefit of dispatch over good old `if` statements.  
So instead of

```julia
f(::a) = ...
f(::b) = ...
f(::c) = ...

```

I would recommend

```julia
function f(x::E)
    if x === a
        ...
    elseif x === b
        ...
    elseif x === c
        ...
    else
        error("Unreachable")
    end
end

```

It looks not as neat, but is equally powerful. If you really insist on the neat syntax I would use a macro to transform it into the `if else` chain.

---

_[View the full topic](https://discourse.julialang.org/t/dispatch-on-enum/77398)._
