julia parametric constructor

39 Views Asked by At

Suppose I write the following julia struct:

struct Foo{S, T}
    v::Vector{S}
    t::T
end

If I want v to be empty by default, I can write a custom constructor

Foo{Int, String}(t::String) = Foo{Int, String}([], t)

Then the following two lines are equivalent:

f = Foo{Int, String}([], "hi")
f = Foo{Int, String}("hi")

But I can only use the convenient custom constructor for Foo{Int, String} objects, not any other type of Foo. How can I write a parametric constructor for a Foo{S, T} which only takes the value of t and initializes v empty?

1

There are 1 best solutions below

0
Przemyslaw Szufel On

Other interesting options beside @DNF's comment:

@kwdef struct Foo{S, T}
    v::Vector{S}=S[]
    t::T
end
Foo{S}(t::T) where {S, T} = Foo(S[], t)

Than you can do:

julia> Foo{Int,Float64}(t=5.0)
Foo{Int64, Float64}(Int64[], 5.0)

julia> Foo{Int}(5.0)
Foo{Int64, Float64}(Int64[], 5.0)