# One of my favorite tricks broken by Julia v1.0

## Aug 18, 2018 · 161 words · 1 minute read julia • types

In Julia v0.6.3 and lower I would write an outer constructor methd that would convert a Dict to my custom type, which I’ve written about before.

This would look something like this:

struct Foo
a::Int
b::Int
end

function Foo(x::Dict)
field_names = String.(fieldnames(Foo))
Foo((get.(x, field_names, nothing))...)
end

I do this because I often work with JSON APIs but also want to take advantage of Julia’s type system once I have the data.

Unfortunately in Julia v1.0 broadcasting over dictionaries is reserved. So instead of broadcasting get you have to use a for loop:

function Foo(d::Dict)
x = []
for f in fieldnames(Foo)
append!(x, get(d, String(f), nothing))
end
Foo(x...)
end

There is another approach which is to just ask for the Dict’s values:

function Foo(d::Dict)
Foo(values(x)...)
end

This works fine so long as there aren’t any extraneous keys. However I prefer to write my outer constructors using a for loop because I, usually, can’t assume that APIs won’t add keys to the payload.