How to make a function accept children of an abstract type?

I have an abstract type “Foo” that has a number of children: “Bar”, “Car”, “Dar”.

I also have a function “f” that takes an array of “Foo” objects as arguments.

function f(a::Array{Foo, 1})

But when I try to run the function with:

julia> typeof(b)
Bar
julia> f([b])

I get an error like:

ERROR: MethodError: no method matching f(::Array{Bar,1})
Closest candidates are: 
f(::Array{Foo,1})

Is there any way to force the function to accept the children of “Foo”? I can’t write methods for every possible array of “Bar” “Dar” and “Car”, so I’m stuck until I can find another solution.

Try

function f(a::Array{<:Foo, 1})

or

function f(a::Array{T, 1}) where T <: Foo

instead.

Array{Foo, 1} is a specific concrete type where each entry in it can be any subtype of Foo independently from one another. Array{<:Foo, 1} on the other hand is the set of all 1D Arrays which contain elements which are subtypes of Foo.

3 Likes

Can you provide an example of that? I am not sure that I understand the difference.

julia> Number[5; 1.2; π]
3-element Array{Number,1}:
 5
 1.2
 π = 3.1415926535897...

julia> Number[5; 1.2; π] isa Vector{Number}
true

julia> [5; 1.2; π]
3-element Array{Float64,1}:
 5.0
 1.2
 3.141592653589793

julia> [5; 1.2; π] isa Vector{Number}
false

julia> [5; 1.2; π] isa Vector{<:Number}
true
3 Likes
julia> A = Number[5; 1.2; π]
3-element Array{Number,1}:
 5
 1.2
 π = 3.1415926535897...

julia> typeof.(A)
3-element Array{DataType,1}:
 Int64
 Float64
 Irrational{:π}

julia> typeof(A)
Array{Number,1}

julia> B = [5; 1.2; π]
3-element Array{Float64,1}:
 5.0
 1.2
 3.141592653589793

julia> typeof.(B)
3-element Array{DataType,1}:
 Float64
 Float64
 Float64

julia> typeof(B)
Array{Float64,1}
3 Likes