Search code examples
dictionaryjuliaabstract-data-type

Define an empty Dict where the values are the subtype of an abstract type


I've got an abstract type, with subtypes. I'd like to make and add to a Dict that holds the subtypes. Is this doable? What's a better way of achieving this?

Example:

abstract type Cat end

struct Lion <: Cat
   manecolour
end

struct Tiger <: Cat
   stripewidth
end

cats = Dict{Int, <:Cat}()

gives

ERROR: MethodError: no method matching Dict{Int64,var"#s3"} where var"#s3"<:Cat()

What's the more correct way of doing this?


Solution

  • Just use the abstract type as the container type: cats = Dict{Int, Cat}():

    julia> cats = Dict{Int, Cat}()
    Dict{Int64,Cat}()
    
    julia> cats[1] = Lion(12)
    Lion(12)
    
    julia> cats
    Dict{Int64,Cat} with 1 entry:
      1 => Lion(12)