Julia Composite Types
A composite type groups named fields into one object. You define one with struct. Julia structs are similar to classes in other languages, except that they hold only data: functions are defined outside the type, and multiple dispatch connects them.
struct Point
x::Float64
y::Float64
end
p = Point(3.0, 4.0)
println(p)
println(p.x, " ", p.y)
println(typeof(p), " ", fieldnames(Point))
distance(a::Point, b::Point) = hypot(a.x - b.x, a.y - b.y)
println(distance(p, Point(0, 0)))Point(3.0, 4.0)
3.0 4.0
Point (:x, :y)
5.0
Julia automatically creates a default constructor that takes one argument per field, in order. Arguments are converted to the field types if possible, which is why Point(0, 0) works with integers.
Immutable by default
A plain struct is immutable: once created, its fields can't be reassigned. Immutable objects are safe to share and can be stored very efficiently (often directly on the stack or inline in arrays).
struct Color
r::UInt8
g::UInt8
b::UInt8
end
c = Color(255, 128, 0)
try
c.r = 0
catch e
println(typeof(e))
end
darker(col::Color) = Color(col.r ÷ 2, col.g ÷ 2, col.b ÷ 2)
println(darker(c))
println(Color(1, 2, 3) == Color(1, 2, 3))ErrorException
Color(0x7f, 0x40, 0x00)
true
To "change" an immutable object, create a new one. Immutable structs with equal fields compare equal with ==.
mutable struct
When an object really represents something that changes over time — a bank account, a game character — declare it mutable struct:
mutable struct Account
owner::String
balance::Float64
end
function deposit!(acc::Account, amount)
amount > 0 || error("deposit must be positive")
acc.balance += amount
return acc
end
acc = Account("Rosa", 100.0)
deposit!(acc, 25.5)
println(acc.balance)
alias = acc
alias.balance = 0
println(acc.balance)
println(Account("x", 1) == Account("x", 1))125.5
0.0
false
Mutable objects have identity: two names can refer to the same account, and two different accounts with equal fields are not == by default (you can define == yourself).
Untyped and abstract fields
Fields may be left untyped (they become Any), but for performance it's best to give fields concrete types, or to use parametric types (next lesson).
struct Labelled
label
value
end
l = Labelled("count", 3)
println(l.label, " = ", l.value)
println(fieldtypes(Labelled))count = 3
(Any, Any)
Building a type hierarchy
Concrete types can declare an abstract supertype with <:. Functions written for the abstract type work for all subtypes, and specific methods override them:
abstract type Shape end
struct Circle <: Shape
r::Float64
end
struct Rect <: Shape
w::Float64
h::Float64
end
area(c::Circle) = π * c.r^2
area(r::Rect) = r.w * r.h
describe(s::Shape) = "$(nameof(typeof(s))) with area $(round(area(s), digits=2))"
shapes = Shape[Circle(1), Rect(2, 3), Circle(0.5)]
for s in shapes
println(describe(s))
end
println("total area: ", round(sum(area, shapes), digits=2))Circle with area 3.14
Rect with area 6.0
Circle with area 0.79
total area: 9.93
Julia has no class inheritance of fields: concrete types can't be subtyped, and abstract types have no fields. Shared behaviour comes from functions defined on the abstract type.
Custom printing
To control how your type prints, add a method to Base.show:
struct Temperature
celsius::Float64
end
Base.show(io::IO, t::Temperature) = print(io, t.celsius, " °C")
t = Temperature(21.5)
println(t)
println([t, Temperature(-3)])21.5 °C
Temperature[21.5 °C, -3.0 °C]
Test yourself
What happens when you assign to a field of an object created from a plain struct?
- The field is updated
- An error is thrown because structs are immutable
- A copy is made
- Nothing happens
Where are methods (functions) for a struct defined in Julia?
- Inside the struct block
- Outside the struct, as ordinary functions
- In a separate class file
- Only in modules
What does struct Circle <: Shape declare?
- Circle inherits Shape's fields
- Circle is a subtype of the abstract type Shape
- Circle is smaller than Shape
- Shape is a subtype of Circle