4

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?.

3
  • How would you like to use T in the constructor? Also, note that the first struct definition does not work on Julia (at least on version 1.8). If you add details and make code more runnable, the answers could be more on point. Commented Oct 19, 2022 at 15:16
  • 2
    I have rewritten the question to put it in context. Commented Oct 19, 2022 at 16:02
  • Now things are clearer. For the definition, you would want struct Archive{T<:Solution} solutions::Vector{T} end. It's usually best to leave things immutable, and you could still push! and modify elements of the solutions vector. In addition, in Julia the compiler infers types for you, so, there is no need to over-specify types (a common instinct for people from statically typed languages). Commented Oct 19, 2022 at 16:27

1 Answer 1

3

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}.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.