Stream: helpdesk (published)

Topic: Surpising dispatch with abstract type parameter


view this post on Zulip DrChainsaw (Jun 05 2022 at 23:44):

Is there some good intuition for the last result of this:

julia> struct AA{T} end

julia> issametype(::AA{T}, x::T) where T = true
issametype (generic function with 1 method)

julia> issametype(::AA, x) = false
issametype (generic function with 2 methods)

julia> issametype(AA{Int}(), 1) #Ok, types are the same
true

julia> issametype(AA{Int}(), 1.0) # Ok, types are not the same
false

julia> issametype(AA{Integer}(), 1) # Uhm...?
true

It happens to do what I want in this case, but I though I needed to define issametype like this:

issametype(::AA{T1}, x::T2) where {T1, T2<:T1} = true

to get the same result as above.

view this post on Zulip Sukera (Jun 06 2022 at 06:11):

julia> 1 isa Integer
true

view this post on Zulip Sukera (Jun 06 2022 at 06:12):

so (AA{Integer}(), 1) matches issametype(::AA{Integer}, ::Integer)

view this post on Zulip Sukera (Jun 06 2022 at 06:13):

the T in your definition is not constrained to concrete types, after all

view this post on Zulip DrChainsaw (Jun 06 2022 at 08:02):

Makes perfect sense. I guess I tripped up on how one is used to writing e.g. isinteger(::AA{<:Integer}) = true, since AA{Integer} is concrete and forgot about the other argument.


Last updated: Oct 02 2023 at 04:34 UTC