Skip to content

Unexpected method dispatch with parametric type constructor #43977

@danielmatz

Description

@danielmatz

In the following example:

julia> struct Foo{T <: Integer}
    x::T
    y::T
end

julia> struct Bar{T}
    x::Foo{T}
    y::Foo{T}
end

julia> methods(Bar)
# 1 method for type constructor:
[1] Bar(x::Foo{T}, y::Foo{T}) where T in Main

julia> Bar(x::Foo, y::Foo) = "generic"

julia> methods(Bar)
# 2 methods for type constructor:
[1] Bar(x::Foo, y::Foo) in Main
[2] Bar(x::Foo{T}, y::Foo{T}) where T in Main

julia> Bar(Foo(1, 2), Foo(1, 2))
"generic"

I had expected the call to Bar to dispatch to the Julia-provided method Bar(::Foo{T}, ::Foo{T}) where T, since the argument types are the same.

In other situations, dispatch does behave according to this expectation. For example:

# Using `Foo` from above

julia> Foo(x::Integer, y::Integer) = "generic"

julia> Foo(1, 2)
Foo{Int64}(1, 2)

julia> Foo(Int8(1), 2)
"generic"

We discussed this on Discourse.

Metadata

Metadata

Assignees

No one assigned

    Labels

    types and dispatchTypes, subtyping and method dispatch

    Type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions