Simplifying Constructors

Is there a better way to define a constructor that allows for optional params or a small amount of logic without having to rewrite all the properties three times?

mutable struct AcRepertoireIrreducibilityAnalysis <: Orderable
    self,
    alpha,
    state,
    direction,
    mechanism,
    purview,
    partition,
    probability,
    partitioned_probability,
    node_labels
    
    function AcRepertoireIrreducibilityAnalysis(
        self,
        alpha,
        state,
        direction,
        mechanism,
        purview,
        partition,
        probability,
        partitioned_probability,
        node_labels=nothing,
    )

    new(
        self,
        alpha,
        state,
        direction,
        mechanism,
        purview,
        partition,
        probability,
        partitioned_probability,
        node_labels
    )
   end
end

Try Parameters.jl. From their documentation,

julia> using Parameters

julia> @with_kw struct A
           a::Int = 6
           b::Float64 = -1.1
           c::UInt8
       end

julia> A(c=4)
A
  a: 6
  b: -1.1
  c: 4

By the way, I think you don’t need your definition of new() which looks like the default constructor anyway. Thus saving you rewriting one time.

This functionality is now also available in Base as Base.@kwdef.

5 Likes