Search code examples
typestype-conversionjuliatype-systems

What is the correct syntax for writing a conversion function (Base.convert) in Julia for a user defined type?


I am trying to define a conversion function (Base.convert).

I tried two different versions of this function for a slightly different syntax and found that some tests I had written worked.

This seems odd, and might be due to some kind of bug in the Julia type system?

Here's a very simple type which I wanted to define implicit conversion functions for a Dict.

import Dates.DateTime

struct Timeseries
    timestamp::Vector{DateTime}
end
function Base.convert(Timeseries, dict::Dict{Symbol, Vector})
    timeseries =
        Timeseries(
            dict[:timeseries],
        )
    return timeseries
end

I also defined this alternative version, which also seemed to work.

function Base.convert(::Type{Timeseries}, dict::Dict{Symbol, Vector})
    timeseries =
        Timeseries(
            dict[:timeseries],
        )
    return timeseries
end

It must be the case that one of these is wrong, but they both appear to work when tested in the REPL.

Why is this?


Examples of usage:

julia> t::Timeseries = Dict{Symbol, Vector}(:timeseries=>[DateTime(2025,1,1)])
Dict{Symbol, Vector} with 1 entry:
  :timeseries => [DateTime("2025-01-01T00:00:00")]

julia> t
Timeseries([DateTime("2025-01-01T00:00:00")])

Solution

  • The form function Base.convert(::Type{Timeseries}, dict::Dict{Symbol, Vector}) looks better, it is similar to the form suggested by the documentation Defining New Conversions.

    The form function Base.convert(Timeseries, dict::Dict{Symbol, Vector}) is just using Timeseries as a parameter name. In this form, the capitalized parameter name Timeseries could be replaced with some other name, such as f, both in the parameter list and in the function call in the body. That would do the same thing, and would be clear that it is not specialized to Timeseries structs.