Multiple Dispatch with Unions, resolving ambiguities

Let’s say we have these methods:

struct Type1 end
struct Type2 end

foo(a::Type1, i) = 1
foo(a::Type2, i) = 2
foo(a::Type1, i::Tuple{}) = 3
foo(b::Type2, i::Tuple{}) = 4

Here, everything dispatches as you would expect. Now let’s say you know that the implementation of the last two methods are identical, you’d probably do this:

bar(a::Type1, i) = 1
bar(a::Type2, i) = 2
bar(a::Union{Type1, Type2}, i::Tuple{}) = 3

But now there’s a MethodError when you try bar(Type1(), ()), saying this is ambiguous.

Shouldn’t a method with a Union parameter act like it was a separate method for each combination of types in the union? Or seen differently, what limitations exist that would make that difficult to do?

4 Likes

This is related: https://github.com/JuliaLang/julia/issues/22404

5 Likes