Function with arg dictionary any not accepting int


#1

I’m trying to define a function that takes in a dictionary of a string to any

function test(t::Dict{String, Any})
    @show t
end

but when I call it with

test(Dict("hi" => 1))

But I get the following error

ERROR: MethodError: no method matching test(::Dict{String,Int64})
Closest candidates are:
  test(!Matched::Dict{String,Any}) at none:2
Stacktrace:
 [1] top-level scope at none:0

Am I misunderstanding the usage of ‘Any’?


#2

In Julia, if T <: S, it does not follow that A{T} <: A{S} (where T and S are types, and A is a parameterized type). In particular, it is not true that Dict{String, Int} <: Dict{String, Any}.

The expression Dict("hi"=>1) creates an object of type Dict{String,Int}. To force it to create an object of type Dict{String,Any}, you need to invoke it as: Dict{String,Any}("hi" => 1).


#3

You can try,

julia> function test(t::Dict{String, <:Any})
           @show t
       end
test (generic function with 1 method)

julia> test(Dict("hi" => 1))
t = Dict("hi"=>1)
Dict{String,Int64} with 1 entry:
  "hi" => 1


#4

or

julia> function test(t::Dict{String, T}) where T
           @show t
       end
test (generic function with 2 methods)

julia> test(Dict("hi" => 1))
t = Dict("hi"=>1)
Dict{String,Int64} with 1 entry:
  "hi" => 1