Distinguish datatype from function

Hello!

Let’s say I want to define a dictionary from Strings to functions:

julia> temp = Dict{String, Function}
Dict{String, Function}

Then I add a value:

julia> temp["abc"] = DateTime
ERROR: MethodError: no method matching setindex!(::Type{Dict{String, Function}}, ::Type{DateTime}, ::String)

What’s up?

maybe temp=Dict{String,Function}() ? (btw, DateTime is a type)

Yes, that’s better. But then I get:

julia> temp["abc"] = DateTime
ERROR: MethodError: Cannot `convert` an object of type Type{DateTime} to an object of type Function

DateTime is a type… wanna refer to its constructor or what?

Yes.

There’s a name conflict here, maybe creating a function datetime(x) = DateTime(x) and then perform your binding ?

1 Like

You can use

temp = Dict{String, Union{Function, Type}}()

If you want to be able to store both functions and types so you can call constructors. Depending on your use case it’s probably marginally more useful than just using a Dict{String, Any} though.

1 Like

That works!