Our
Our

Reputation: 1035

Outer constructor with fewer argument

I want to do something like

struct Test
    nParticles::Int64
    particleIDs::Vector{Particle}
    function Test(nParticles::Int32)
        particleIDs = createPmarticles(nParticles)
        ...
    end
end

such that the variable particleIDs is defined inside the type with the help of the first argument nParticles and the function createPmarticles (which is defined somewhere else).

The question is this type of outer constructor is not allowed as far as I can see

LoadError: LoadError: invalid redefinition of type Test

So, is there a way to accomplish this?

Upvotes: 2

Views: 55

Answers (1)

Przemyslaw Szufel
Przemyslaw Szufel

Reputation: 42214

You could do:

struct Test
    nParticles::Int64
    particleIDs::Vector{String}
    Test(nParticles::Int32) = new(nParticles, [string(i) for i in 1:nParticles])
end

And now some test:

julia> Test(Int32(3))
Test(3, ["1", "2", "3"])

Note that this has covered the default constructor so now when you write Test(1,["nnn"]) you will get an error. If you rather want to have an additional external constructor you can define it outside of struct such as (note that struct Test2 is not using the new constructor):

struct Test2
    nParticles::Int64
    particleIDs::Vector{String}
end
Test2(nParticles::Int32) = Test2(nParticles, [string(i) for i in 1:nParticles])

Now this can be used:

julia> Test2(Int32(3))
Test2(3, ["1", "2", "3"])

But you can still do:

julia> Test2(1,["nnn"])
Test2(1, ["nnn"])

Upvotes: 2

Related Questions