Trouble with multiple dispatch on Arrays


#1

Im having some trouble understanding why the following does not work:

julia>  f(x::Array{Integer,1}) = print("test")
f (generic function with 1 method)

julia> f([1,3,3])
ERROR: MethodError: no method matching f(::Array{Int64,1})
Closest candidates are:
  f(::Array{Integer,1}) at REPL[5]:1
Stacktrace:
 [1] top-level scope at none:0

As I understand it, Integer is a more generic type than Int64, so why doesn’t Julia use the method I defined for Integers even if when I enter [1,2,3] into the console it is of type Array{Int64,1}


#2

This is because, to cite the docs, “in the parlance of type theory, Julia’s type parameters are invariant , rather than being covariant (or even contravariant)”

You probably want:

julia> f(x::Array{T,1}) where T <: Integer = print("test")
f (generic function with 1 method)

julia> f([1,2,3])
test

#3

You can also write this more compactly as

f(x::Array{<:Integer,1}) = print("test")

#4

Also,

julia> f(x::Vector{<:Integer}) = print("test")
f (generic function with 5 methods)

julia> f([1,3,3])
test