Reputation: 15552
I found that Array
in Julia is not covariant and subtypes of Number
are not auto-converted to supertypes.
What I mean is, for example,
head(a::Vector{Number}) = a[1]
or head(a::Vector{Real}) = a[1]
cannot execute head([1, 2, 3])
,
whereas head(a::Vector{T}) where {T <: Number} = a[1]
or head(a::Vector{T}) where {T <: Real} = a[1]
can.
Is there a reason for this behavior in Julia?
Upvotes: 4
Views: 67
Reputation: 10984
See this section in the manual: https://docs.julialang.org/en/stable/manual/types/#Parametric-Composite-Types-1 which explains this. Note that there is a short form for head(a::Vector{T}) where {T <: Number} =...
(which you can use unless you use T
in the function body):
head(a::Vector{<:Number}) =...
Upvotes: 5