Your two methods for function same_type
have a different signature:
- The first one has signature
Tuple{typeof(same_type), T, T} where T
- The second one has signature
Tuple{typeof(same_type), Any, Any}
(here is a programmatic way of getting these method signatures)
The list of defined methods can be accessed with methods
:
julia> methods(same_type)
# 2 methods for generic function "same_type" from Main:
[1] same_type(x::T, y::T) where T
@ REPL[18]:1
[2] same_type(x, y)
@ REPL[23]:1
To get the signature for each method, ask for the sig
field:
julia> methods(same_type)[1].sig
Tuple{typeof(same_type), T, T} where T
julia> methods(same_type)[2].sig
Tuple{typeof(same_type), Any, Any}
When a function is called, for example when you call same_type(1, 2)
, the signature of your call will be compared to the signatures of all the methods of that function. The signature of your call is Tuple{typeof(same_type), Int, Int}
in this particular case and it is a subtype of both method signatures:
julia> Tuple{typeof(same_type), Int, Int} <: Tuple{typeof(same_type), T, T} where T
true
julia> Tuple{typeof(same_type), Int, Int} <: Tuple{typeof(same_type), Any, Any}
true
so both methods are eligible. But the first one is more specific than the second one, because the signature of the first method is a subtype of the signature of the second method. Indeed:
julia> (Tuple{typeof(same_type), T, T} where T) <: Tuple{typeof(same_type), Any, Any}
true
while the converse is not true (otherwise the two signatures would be the same):
julia> Tuple{typeof(same_type), Any, Any} <: Tuple{typeof(same_type), T, T} where T
false
and thus, the first method is called and not the second.
The intuition is explained in Methods · The Julia Language and the nitty-gritty details of subtyping can be found in More about types · The Julia Language. In particular, the last subsection goes into more details about what is “method specificity”.
Best is probably to watch Jeff Bezanson explaining the rules though. I highly recommend https://www.youtube.com/live/TPuJsgyu87U?si=Nw_1STjfpEPQS27w&t=985 (the entire talk is great, the section starting at 16’25 is probably what you are most interested in for this particular question).