Question about the selection mechanism of multiple dispatch

Yes. A type T is always more specific than Union{T, X} for some other type X, so a method defined with ::T as its argument will be more specific than one with ::Union{T, X} (assuming no change in the other arguments).

A few examples:

  • foo(::T) is more specific than foo(::Union{T, X})
  • foo(::T, ::X) is more specific than foo(::Union{T, X}, ::X)
  • foo(::T, ::X) is more specific than foo(::T, ::Union{T, X})
  • foo(::T, ::X) is more specific than foo(::Union{T, X}, ::Union{T, X})

But there are ambiguous cases:

  • foo(::Union{T, X}, ::X) is ambiguous with (neither more nor less specific than) foo(::T, ::Union{T, X})

If there is no unique most-specific method, then Julia will throw an ambiguity error, so there’s no need to worry about one method being arbitrarily preferred.

6 Likes