Type inheritance in function arguments

2019-07-25 19:12发布

I'm having an issue with type in functions, I've managed to write the minimal code that explains the problem:

immutable Inner{B<:Real, C<:Real}
a::B
c::C
end

immutable Outer{T}
    a::T
end

function g(a::Outer{Inner})
    println("Naaa")
end

inner = Inner(1, 1)
outer = Outer(inner)

g(outer)

Will lead to the method error MethodError: no method matching g(::Outer{Inner{Int64,Int64}}) So basically, I don't want to have to say what the types of Inner are, I just want the function to make sure that it's an Outer{Inner} and not Outer{Float64} or something.

Any help would be appreciated

1条回答
ら.Afraid
2楼-- · 2019-07-25 19:58

Type Inner{Int64,Int64} is a concrete Inner type and it's not a subtype of Inner{Real, Real}, since different concrete types of Inner (Int64 or Float64) can have different representations in memory.

According to the documentation, function g should be defined as:

function g(a::Outer{<:Inner})
    println("Naaa")
end

so it can accept all arguments of type Inner.

Some examples, after define g with <::

# -- With Float32 --

julia> innerf32 = Inner(1.0f0, 1.0f0)
Inner{Float32,Float32}(1.0f0, 1.0f0)

julia> outerf32 = Outer(innerf32)
Outer{Inner{Float32,Float32}}(Inner{Float32,Float32}(1.0f0, 1.0f0))

julia> g(outerf32)
Naaa

# -- With Float64 --

julia> innerf64 = Inner(1.0, 1.0)
Inner{Float64,Float64}(1.0, 1.0)

julia> outerf64 = Outer(innerf64)
Outer{Inner{Float64,Float64}}(Inner{Float64,Float64}(1.0, 1.0))

julia> g(outerf64)
Naaa

# -- With Int64 --

julia> inneri64 = Inner(1, 1)
Inner{Int64,Int64}(1, 1)

julia> outeri64 = Outer(inneri64)
Outer{Inner{Int64,Int64}}(Inner{Int64,Int64}(1, 1))

julia> g(outeri64)
Naaa

More details at the documentation: Parametric Composite Type

查看更多
登录 后发表回答