Why doesn't Julia's Dict{String, Any} accept 'any' value

Viewed 107

I wrote a function that should take a Dict{String, <anything>} (so with any value). However when I specify the required parameter as Dict{String, Any} the function only takes the explicit Dict{String, Any}. Is there a way to let a Dict take any value?

function funky(arg::Dict{String, Any})
    return "Oh, hi mark."
end
julia> funky(Dict("Oh" => [0 1; 2 3]))
ERROR: MethodError: no method matching funky(::Dict{String,Array{Int64,2}})
Closest candidates are:
  funky(::Dict{String,Any})

julia> funky(Dict{String, Any}("Oh" => [0 1; 2 3]))
"Oh, hi mark."
2 Answers

If you write it as in your first version of funky, the function does not expect any type but exactly type Any, whereas in the following definition,

julia> function funky(arg::Dict{String, <:Any})
  return "Oh, hi mark."
end

julia> funky(Dict("Oh" => [0 1; 2 3]))
"Oh, hi mark."

any subtype of Any is accepted (so all types), which is due to the subtype operator <:. You did this implicitly in your second version. So to wrap it up the main difference is:

julia> typeof([0 1; 2 3]) == Any # first verion
false

julia> typeof([0 1; 2 3]) <: Any # second version
true

I found this solution.

function funky(arg::Dict{String, T}) where T
    return "Oh, hi mark."
end

Which according to the docs is just syntactic sugar for:

function funky(arg::Dict{String, T}) where T <: Any
    return "Oh, hi mark."
end
julia> funki(Dict("Oh" => [0 1; 2 3]))
"Oh, hi mark."

However, I still don't fully understand why Dict{String, Any} shouldn't work either. Maybe somebody with more knowledge could explain.

Related