TExcelTAD
Home › Julia › Julia Constructors

Julia Constructors

A constructor is a function that creates a new object of a type. Julia gives every struct a default constructor, and you can add your own to provide defaults, convert arguments, or enforce rules (invariants) about valid objects.

The default constructor

julia · try it yourself
struct Book
    title::String
    pages::Int
end

b = Book("Emma", 474)
println(b)
println(Book("Short", 12.0))      # 12.0 is converted to Int
try
    Book("Odd", 12.5)
catch e
    println(typeof(e))
end
Book("Emma", 474)
Book("Short", 12)
InexactError

Outer constructors

An outer constructor is simply another method of the type's name, defined outside the struct block. It usually fills in defaults or accepts different inputs, then calls an existing constructor:

julia · try it yourself
struct Rect
    width::Float64
    height::Float64
end

Rect(side::Real) = Rect(side, side)                 # a square
Rect(; width=1.0, height=1.0) = Rect(width, height) # keyword version
Rect(dims::Tuple) = Rect(dims...)

println(Rect(2, 3))
println(Rect(5))
println(Rect(height=4))
println(Rect((7, 8)))
Rect(2.0, 3.0)
Rect(5.0, 5.0)
Rect(1.0, 4.0)
Rect(7.0, 8.0)

Inner constructors and invariants

An inner constructor is defined inside the struct block and calls the special function new to create the object. Once you define one, the default constructor disappears, so every object must pass through your checks:

julia · try it yourself
struct Percentage
    value::Float64
    function Percentage(v::Real)
        0 <= v <= 100 || throw(ArgumentError("percentage must be in 0..100, got $v"))
        return new(v)
    end
end

println(Percentage(42).value)
try
    Percentage(120)
catch e
    println(sprint(showerror, e))
end
42.0
ArgumentError: percentage must be in 0..100, got 120

Inner constructors are the right place for invariants — rules that must hold for every object, such as "the minimum is not larger than the maximum".

julia · try it yourself
struct Range2
    lo::Int
    hi::Int
    function Range2(a, b)
        lo, hi = minmax(a, b)        # normalise instead of rejecting
        new(lo, hi)
    end
end

println(Range2(3, 9))
println(Range2(9, 3))
Range2(3, 9)
Range2(3, 9)

Constructors for parametric types

For a parametric struct, Julia creates constructors that infer the type parameter. An inner constructor of a parametric type is written with where and new{T}:

julia · try it yourself
struct Sorted{T}
    items::Vector{T}
    Sorted{T}(v::AbstractVector) where {T} = new{T}(sort(collect(v)))
end
Sorted(v::AbstractVector{T}) where {T} = Sorted{T}(v)   # infer T

s = Sorted([5, 3, 8, 1])
println(s.items, " ", typeof(s))
f = Sorted{Float64}([2, 1])
println(f.items, " ", typeof(f))
[1, 3, 5, 8] Sorted{Int64}
[1.0, 2.0] Sorted{Float64}

Defining the inner constructor removes the automatic inferring constructor, so we add the outer Sorted(v) method back.

Incomplete initialisation

Inside an inner constructor of a mutable struct, new() may be called with fewer arguments than fields. The remaining fields stay undefined until assigned. This is how self-referencing objects, like a node that points to itself, can be built:

julia · try it yourself
mutable struct Node
    value::Int
    next::Node
    Node(v) = (n = new(v); n.next = n; n)   # a one-node circular list
end

a = Node(1)
println(a.next === a)
println(a.next.next.value)
true
1

Keyword-based constructors with @kwdef

For types with many fields, Base.@kwdef generates a keyword constructor with default values:

julia · try it yourself
Base.@kwdef struct Config
    host::String = "localhost"
    port::Int = 8080
    debug::Bool = false
end

println(Config())
println(Config(port=3000, debug=true))
Config("localhost", 8080, false)
Config("localhost", 3000, true)

Test yourself

What happens to the default constructor when you define an inner constructor?

  1. It still exists
  2. It is no longer provided
  3. It becomes private
  4. It is renamed to new

Which special function creates the object inside an inner constructor?

  1. new
  2. init
  3. self
  4. create

Where is an outer constructor defined?

  1. Inside the struct block
  2. Outside the struct, as a method named after the type
  3. In a module called Constructors
  4. With the constructor keyword