Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Julia parametric constructor and incomplete initialization

I'm new to programming in Julia (I'm coming from Java) and some Julia concepts are still difficult to understand to me. What I intend is to replicate this Java code:

public class Archive<T extends Solution> {
  public List<T> solutions;

  public Archive() {
    solutions = new ArrayList<>() ;
  }
}

Then, I have defined the following Julia struct:

mutable struct Archive{T <: Solution}
  solutions::Vector{T}
end

and I would like to define a constructor to inialize empty archives. In the case of an external constructor, I think that the code would look like this:

function Archive()
  return Archive([])
end

Would it be possible to modify the constructor somehow to include the parametric type T?.

like image 677
Antonio Avatar asked Oct 18 '25 03:10

Antonio


1 Answers

This is most likely the constructor you want:

Archive(T::Type{<:Solution}=Solution) =Archive(T[])

Then you can write Archive() or Archive(SomeType) if SomeType is a subtype of Solution.

Note that your definition:

function Archive()
  return Archive([])
end

Is incorrect unless Solution is Any (and most likely it is not). You will get an error as [] is Vector{Any} and you require Archive to store subtypes of Vector{<:Solution}.

like image 143
Bogumił Kamiński Avatar answered Oct 20 '25 23:10

Bogumił Kamiński