Composite types in Julia: Dictionaries as a named field?
Asked Answered
E

2

5

I'd like to make a composite type that includes a dictionary as one of its named fields. But the obvious syntax doesn't work. I'm sure there's something fundamental that I don't understand. Here's an example:

type myType
    x::Dict()
end

Julia says: type: myType: in type definition, expected Type{T<:Top}, got Dict{Any,Any} which means, I'm guessing, that a dictionary is not a of Any as any named field must be. But I'm not sure how to tell it what I mean.

I need an named field that is a dictionary. An inner constructor will initialize the dictionary.

Ettieettinger answered 27/5, 2015 at 15:6 Comment(0)
G
9

There's a subtle difference in the syntax between types and instances. Dict() instantiates a dictionary, whereas Dict by itself is the type. When defining a composite type, the field definitions need to be of the form symbol::Type.

That error message is a little confusing. What it's effectively saying is this:

in type definition, expected something with the type Type{T<:Top}, got an instance of type Dict{Any,Any}.

In other words, it expected something like Dict, which is a Type{Dict}, but instead got Dict(), which is a Dict{Any,Any}.

The syntax you want is x::Dict.

Growing answered 27/5, 2015 at 15:47 Comment(0)
S
5

Dict() creates a dictionary, in particular a Dict{Any,Any} (i.e. keys and values can have any type, <:Any). You want the field to be of type Dict, i.e.

type myType
    x::Dict
end

If you know the key and value types, you could even write, e.g.

type myType
    x::Dict{Int,Float64}
end
Starchy answered 27/5, 2015 at 15:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.