I have some code that starts with a loosely type Dict (e.g. something returned from a web service). I want to write a function that will extract a certain key from it, convert that key into a concretely-typed array (Array{Int64, 1}
), and return it. It is known (by me) that the particular key actually does have this type, and is a valid key. Whilst I donβt mind if the internals of this function are a bit dynamic / could raise an exception, I would like the return type of this function to be correctly inferred as Array{Int64, 1}
. I canβt find a way to do that: the return type is inferred as Any
:
julia> foo(x) = Array{Int64}(x["asd"])
foo (generic function with 1 method)
julia> a = Dict{String, Any}("asd" => Any[1,2,3])
Dict{String,Any} with 1 entry:
"asd" => Any[1, 2, 3]
julia> typeof(a["asd"])
Array{Any,1}
julia> @code_warntype foo(a)
Body::Any
1 1 β %1 = invoke Base.ht_keyindex(_2::Dict{String,Any}, "asd"::String)::Int64 ββ» getindex
β %2 = (Base.slt_int)(%1, 0)::Bool βββ» <
βββ goto #3 if not %2 ββ
2 β %4 = %new(Base.KeyError, "asd")::KeyError βββ» Type
β (Base.throw)(%4) ββ
βββ $(Expr(:unreachable)) ββ
3 β %7 = (Base.getfield)(x, :vals)::Array{Any,1} βββ» getproperty
β %8 = (Base.arrayref)(false, %7, %1)::Any βββ» getindex
βββ goto #5 ββ
4 β $(Expr(:unreachable)) ββ
5 β %11 = (Array{Int64,N} where N)(%8)::Any β
βββ return %11 β
Could someone please help me work out what branches / thing / corner case Iβm missing here that will help the compiler infer the desired return type?
EDIT: perhaps an even simpler example:
julia> a = Dict{String, Any}("asd" => Int64)
Dict{String,Any} with 1 entry:
"asd" => Int64
julia> foo(x) = Int64(x["asd"])
foo (generic function with 1 method)
julia> @code_warntype foo(a)
Body::Any
1 1 β %1 = invoke Base.ht_keyindex(_2::Dict{String,Any}, "asd"::String)::Int64 ββ» getindex
β %2 = (Base.slt_int)(%1, 0)::Bool βββ» <
βββ goto #3 if not %2 ββ
2 β %4 = %new(Base.KeyError, "asd")::KeyError βββ» Type
β (Base.throw)(%4) ββ
βββ $(Expr(:unreachable)) ββ
3 β %7 = (Base.getfield)(x, :vals)::Array{Any,1} βββ» getproperty
β %8 = (Base.arrayref)(false, %7, %1)::Any βββ» getindex
βββ goto #5 ββ
4 β $(Expr(:unreachable)) ββ
5 β %11 = (Main.Int64)(%8)::Any β
βββ return %11 β