Struggling with collection types

Still trying to get my head around the finesses of type hierarchies :slight_smile:

I created the following struct:

struct Price
    components::Dict{String, Float64}
    precision::Int64
    Price(;precision::Integer) = new(Dict{String, Float64}(), precision)
end

function Price(components::Dict{String, <:Real}; precision::Integer = 2)
    price = Price(precision = precision)

    for entry in keys(components)
        price.components[key] = round(components[key], digits = precision)
    end

    return price
end

Price(components::AbstractVector{Pair{String, <:Real}}; precision::Integer = 2) = Price(Dict{String, Float64}(components), precision = precision)

Base.getindex(price::Price, index:: String) = price.components[index]
Base.setindex!(price::Price, amount::Real, index:: String) = (price.components[index] = round(amount, digits = price.precision))

I expected the following call to succeed:

Price(["c1" => 50, "c2" => 150])

But alas, I get the following error:

ERROR: MethodError: no method matching Price(::Array{Pair{String,Int64},1})
Closest candidates are:
  Price(; precision) at /Users/stef/Programming/Julia Projects/loreco-abm/src/finance/price.jl:7
  Price(::Dict{String,var"#s44"} where var"#s44"<:Real; precision) at /Users/stef/Programming/Julia Projects/loreco-abm/src/finance/price.jl:10
  Price(::AbstractArray{Pair{String,var"#s47"} where var"#s47"<:Real,1}; precision) at /Users/stef/Programming/Julia Projects/loreco-abm/src/finance/price.jl:20
Stacktrace:
 [1] top-level scope at none:1

Iā€™m pretty sure Iā€™m overlooking something obvious here but to be honest I have no clue what.

Thanks in advance,
Stef

Hi,

The following works:

function Price(components::Dict{String, <:Real}; precision::Integer = 2)
    price = Price(precision = precision)

    for entry in keys(components)
        price.components[entry] = round(components[entry], digits = precision)
    end

    return price
end

Price(components::AbstractVector{<:Pair{String, <:Real}}; precision::Integer = 2) = Price(Dict{String, Float64}(components), precision = precision)

You used key instead of entry and your AbstractVector needs to be of <:Pairs.

2 Likes