Method Error : Not identifying Integer as Any

A smaller MWE would be

julia> f(d::Dict{Int, Any}) = println(keys(d))

julia> f(Dict(1=>1, 2=>"a"))
[2, 1]

julia> f(Dict(1=>1, 2=>2))
ERROR: MethodError: no method matching f(::Dict{Int64, Int64})
Closest candidates are:
  f(::Dict{Int64, Any}) at REPL[3]:1
Stacktrace:
 [1] top-level scope
   @ REPL[4]:1

what you actually want is

julia> g(d::Dict{Int, T}) where T <: Any  = println(keys(d))
g (generic function with 1 method)

julia> g(Dict(1=>1, 2=>"a"))
[2, 1]

julia> g(Dict(1=>1, 2=>2))
[2, 1]

As although Any sounds general, it is, in f’s context, a specific type of Dict, so only one method will be created - one that unboxes the Any of the values.

Whereas in g’s context, a method for each type T can be generated specialised on the type of T.

3 Likes