glwhart
glwhart

Reputation: 334

Composite types in Julia: Dictionaries as a named field?

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.

Upvotes: 5

Views: 549

Answers (2)

mbauman
mbauman

Reputation: 31342

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.

Upvotes: 9

IainDunning
IainDunning

Reputation: 11644

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

Upvotes: 5

Related Questions