A constructor makes an instance of a type. Define a Julia composite type, and Julia supplies a constructor with the type’s name. It accepts values for the fields; you can add methods that accept a more convenient set of inputs. section 8.3
Where you define a custom method changes what callers can do:
- An outer constructor sits outside the struct definition and adds a method alongside Julia’s defaults. It can fill in a value the caller omits, such as a tank’s propellant mass. section 8.3 section 8.4
- An inner constructor sits inside the struct definition and replaces the default methods. It calls new to create the instance, so callers cannot bypass its chosen initialization through a default constructor. section 8.4
Listing 8.9 Defining an inner constructor for FlexiTank
mutable struct FlexiTank <: Tank
drymass::Float64
totalmass::Float64
propellant::Float64
function FlexiTank(drymass::Number, totalmass::Number)
new(drymass, totalmass, totalmass - drymass) #1
end
end
The inner FlexiTank constructor accepts dry mass and total mass, then computes propellant mass rather than accepting it independently. section 8.4
Constructor methods can also hide an inconvenient representation. An angle stored as total seconds can be made through Degree, Minute, and Second functions that accept familiar components and produce DMS values. section 9.3.1
Listing 9.3 Angle constructors for degrees, minutes, and seconds
Degree(degrees::Integer) = Minute(degrees * 60) Degree(deg::Integer, min::Integer) = Degree(deg) + Minute(min) function Degree(deg::Integer, min::Integer, secs::Integer) Degree(deg, min) + Second(secs) end function Minute(minutes::Integer) DMS(minutes * 60) end function Second(seconds::Integer) DMS(seconds) end
These short constructor functions turn degrees, minutes, and seconds into the underlying DMS representation. section 9.3.1
Using a constructor for numeric conversion
To request a numeric type, call it like a function: Float64(1//2) produces 0.5. A conversion can fail when the target type cannot represent the value, as with Int8(1000). Julia uses convert, rather than the constructor, for certain implicit conversions. section 9.2












