Compatibility of Dict{String, Any} with Dict{String, String}



Hi all. I’m trying to pass an argument of type Dict{String, String} to a function with signature Dict{String, Any}, e.g.,

function foo(x::Dict{String, Any})

When I invoke it like so:


I get

ERROR: MethodError: no method matching foo(::Dict{String,String})
Closest candidates are:
  foo(::Dict{String,Any}) at REPL[18]:2

I’m confused by this. Doesn’t a Dict{String, String} fall under the Dict{String, Any} category? I guess this is related to the disclaimer in Parametric Composite Types, namely:

This last point is very important: even though Float64 <: Real we DO NOT have Point{Float64} <: Point{Real}.

What would be the correct thing to do here? I expect to pass Dicts keyed by String with arbitrary value types to foo (think JSON objects), but I don’t want foo to fail if the Dict happens to have the same type for all its values.

julia> function foo(x::Dict{String, <:Any})
foo (generic function with 1 method)

julia> foo(Dict("bar"=>"baz"))
Dict{String,String} with 1 entry:
  "bar" => "baz"

You just need to read the next few paragraphs below the big orange “Warning” from your link to find this in the docs.


foo(x::Dict{String,<:Any}) = ... is a useful shorthand here. This is explained in manual immediately after the warning you quoted. Even better, just do foo(x::Dict{String}) = ... (since omitted trailing type parameters are equivalent to <:Any).


D’oh. Thanks.