I’ve got a type defined as Union{Dict{Union{UInt8, String}, Number}, Nothing}
. This works, but as soon as I add String
to this Union
it breaks and does not accept the initially working values anymore. See MWE below.
The error is:
ERROR: MethodError: Cannot `convert` an object of type
Dict{UInt8, Float64} to an object of type
Union{Dict{Union{UInt8, String}, Number}, String}
(respectively [...] Dict{String, Float64} to an object of type [...]
for the Dict
using String
keys in the MWE)
Why does this work the way it does? And what’s the best solution to achieve that?
Base.@kwdef struct MyStruct1
val::Union{Dict{Union{UInt8, String}, Number}, Nothing} = nothing
end
Base.@kwdef struct MyStruct2
val::Union{Dict{Union{UInt8, String}, Number}, String, Nothing} = nothing
end
x = Dict(0x1 => 1.0, 0x2 => 1.0)
y = Dict("1" => 1.0, "2" => 1.0)
MyStruct1() # MyStruct1(nothing)
MyStruct1(x) # MyStruct1(Dict{Union{UInt8, String}, Number}(0x02 => 1.0, 0x01 => 1.0))
MyStruct1(y) # MyStruct1(Dict{Union{UInt8, String}, Number}("1" => 1.0, "2" => 1.0))
MyStruct2() # MyStruct2(nothing)
MyStruct2(x) # this fails
MyStruct2(y) # this fails
Remark: This stays the same if changing Number
to Float64
explicitly.
Edit: It works when falling back down to Union{Dict, _String, Nothing}
, but I actually need the correct type, that the Dict
values are Number
for some internal conversion to work correctly (so it’s not only about fully specifying the type, it actually breaks functionality).