Dispatch on enum

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

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

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

I would recommend

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.

2 Likes