Awkward case with multiple-dispatch and type heirachy

The type hierarchy in Julia is a tree. If you need some other division or want to step out of the hierarchy, you can use the Holy trait pattern:

struct Default end
struct Special end

f(foo) = _f(foo, traitof(foo))

traitof(x) = Default()
traitof(x::AbstractVector{T}) where {T<:Integer} = if T == Bool; Default() else Special() end

_f(foo, ::Default) = :fallback_logic
_f(foo, ::Special) = :special_logic

This actually quite similar to how types can be assigned to traits in Rust, but more flexible in that it readily works with multiple dispatch.

7 Likes