JULIA / CHAPTER 07

Composite types and multiple dispatch

Advanced

Model state and select behavior from argument types.

By the end of this chapter

  • Distinguish struct from mutable struct
  • Define methods for related types
  • Explain dispatch across multiple arguments

The idea

A struct defines a composite type with named fields. Its fields cannot be reassigned after construction, while a mutable struct permits field reassignment. This distinction concerns the fields themselves: a vector stored inside an immutable structure can still be mutated. Choose mutability from the object’s responsibilities, and use constructors or controlled operations when invalid states would undermine the rest of the program.

Julia functions can have several methods distinguished by their argument types. Multiple dispatch selects an applicable method using the types of all arguments, rather than treating only the first argument as a special receiver. Define a general operation and add specific methods when behavior differs by representation. Overlapping signatures can create ambiguity, so check whether a call has one clearly most-specific applicable method.

Julia example
abstract type Ticket end
struct Standard <: Ticket
    cost::Int
end
struct Discounted <: Ticket
    cost::Int
    discount::Int
end
price(t::Standard) = t.cost
price(t::Discounted) = t.cost - t.discount
println(price(Standard(10)))
println(price(Discounted(10, 3)))
Result
10
7

The same function name has two methods. Each argument’s concrete type selects the corresponding calculation, allowing callers to request price without branching on the representation.

Try it yourself

Define two shape types and an area method for each, then calculate a total through the shared function name.

Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.

CHECK YOUR UNDERSTANDING

Chapter checkpoint

Which declaration permits direct reassignment of an instance’s count field?