Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 40 ยท Types and Dispatch

Multiple Dispatch

Learn Julia's core idea, multiple dispatch: functions with many methods, choosing by every argument, ambiguity errors, and extending existing functions.

If you remember one thing about Julia, make it this: a function is a name, and the code that runs is a method chosen from the types of all the arguments. This is called multiple dispatch, and it shapes how Julia programs are organized, why libraries combine so well, and why the compiler can make code fast.

In object-oriented languages, a.collide(b) picks the code from the type of a alone. In Julia, you write collide(a, b) and the choice depends on both types. In this lesson you will define methods, see how Julia picks the most specific one, meet the ambiguity error, add methods to functions you did not write, and compare the design with OOP. Julia is not installed on this site, so the Julia is read-only; the runnable example is a small Python simulation of the dispatch rules.

Functions and methods

A function can have many methods. Each method is one definition with its own argument types:

JULIA
describe(x) = "something"
describe(x::Number) = "a number"
describe(x::Integer) = "an integer"
describe(x::String) = "a string"

describe(3)         # "an integer"
describe(3.5)       # "a number"
describe("hi")      # "a string"
describe(:sym)      # "something"

All four lines add methods to the single function describe. When you call it, Julia looks at the runtime types of all arguments and picks the most specific method that applies. For describe(3), three methods fit (Any, Number, Integer), and Integer is the most specific. You can list them:

JULIA
methods(describe)
# 4 methods for generic function "describe": ...

Specific means "lower in the type hierarchy". A method for Integer beats one for Number, which beats one for Any. An unannotated argument is the same as ::Any.

How a call is resolved

You call f(a, b) Julia reads the types of every argument.
Find matches Keep each method that fits all arguments.
Pick most specific The lowest types in the hierarchy win.
Compile and run A fast version is made for those exact types.
1 / 2

Dispatch on every argument

The word multiple is about arguments beyond the first. Here is a classic pair of types and a function whose behavior depends on both:

JULIA
abstract type Body end
struct Asteroid <: Body end
struct Ship <: Body end

collide(a::Asteroid, b::Asteroid) = "rocks bounce"
collide(a::Asteroid, b::Ship)     = "ship is damaged"
collide(a::Ship, b::Asteroid)     = collide(b, a)     # symmetric: reuse
collide(a::Ship, b::Ship)         = "ships dock"
collide(a::Body, b::Body)         = "something collides"

collide(Asteroid(), Ship())   # "ship is damaged"
collide(Ship(), Asteroid())   # "ship is damaged"
collide(Ship(), Ship())       # "ships dock"

In a single-dispatch language you would put collide inside a class and then use isinstance checks or the visitor pattern for the second argument. Julia makes the "table" of cases explicit: one method per cell, and the compiler selects the cell.

Julia uses this for ordinary arithmetic, too. The expression 1 + 2.5 calls +(::Int64, ::Float64). The standard library has a method that promotes the integer to a float and then calls the Float64 addition. You can see them with methods(+), a list of over a hundred entries.

Method ambiguity

Julia never guesses. If two methods both fit and neither is more specific, the call fails:

JULIA
f(x::Int, y) = "first is Int"
f(x, y::Int) = "second is Int"

f(1, "a")   # "first is Int"
f("a", 1)   # "second is Int"
f(1, 2)     # ERROR: MethodError: f(::Int64, ::Int64) is ambiguous

For f(1, 2) both methods apply, and each is better in a different argument. The fix is to define the case that resolves the tie:

JULIA
f(x::Int, y::Int) = "both are Int"
f(1, 2)     # "both are Int"

Ambiguities are most common when two packages each add methods for generic argument types. Defining the intersection method is the standard cure, and Test.detect_ambiguities finds them in a package.

Adding methods to functions you did not write

Because methods belong to functions, not to types, you can add a method for your type to any existing function. This is what makes Julia libraries compose. Here a Money type learns to use + and to be shown nicely:

JULIA
struct Money
    cents::Int
end

Base.:+(a::Money, b::Money) = Money(a.cents + b.cents)
Base.show(io::IO, m::Money) = print(io, "\$", m.cents รท 100, ".", lpad(m.cents % 100, 2, '0'))

Money(250) + Money(199)    # $4.49
sum([Money(100), Money(50), Money(25)])   # $1.75

Once + works for Money, any code written in terms of +, such as sum, works with it, even though the author of sum never heard of Money. This is why packages written independently, a plotting library and an automatic differentiation library, can work together on the same custom types.

The caution is type piracy: do not add a method to someone else's function for someone else's types. Defining Base.:+(a::String, b::String) changes the meaning of + for every program that loads your code. Extending + for your own type is fine.

Comparison with OOP

Question Class-based OOP Julia
Where does behavior live? Inside the class In functions, outside the data
Choice depends on The receiver (a in a.f(b)) All arguments
Add behavior to an existing type Subclass or monkey patch Add a method, no change to the type
Data inheritance Subclasses inherit fields Structs never inherit fields

The trade-off: Julia gives you flexibility and speed, but "what methods does this type have?" is answered by searching functions (methods(f), or methodswith) rather than by reading one class. Good Julia code keeps the generic function names meaningful and documents the contract of each.

A simulation in Python

Python dispatches on the first argument only, but we can build a small multiple-dispatch table to see the selection rules. The register decorator stores each method with its types, and call finds all applicable methods and chooses the most specific, or reports ambiguity.

Python Choosing the most specific method

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The last line shows the fallback: there is no Ship, Ship method here, so the general Body, Body one runs. In real Julia, the compiler builds this table and does the selection at compile time whenever the argument types are known.

The next stand-in recreates the ambiguity error and shows how defining the intersection method fixes it.

Python Ambiguity and its fix

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The simulation uses Python's runtime class checks. Real Julia does the same selection but ahead of time and without the call overhead, which is why dispatch is not a cost to avoid.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In Julia, what is a method?

    A function name can have many methods. Each one is a definition with its own argument type signature.
  2. 2. What does multiple dispatch choose a method by?

    Julia considers every argument. That is what separates it from single dispatch, where only the receiver decides.
  3. 3. Given f(x::Int, y) and f(x, y::Int), what happens on f(1, 2)?

    Neither method is more specific than the other. Julia refuses to guess; defining f(x::Int, y::Int) resolves it.
  4. 4. Which is an example of type piracy?

    Adding a method to someone else's function for only someone else's types changes behavior for every program that loads the code.

Summary

  • A Julia function is a name with many methods; the call picks the most specific method that fits all argument types.
  • Dispatch looks at every argument, not only the first, which replaces visitor patterns and long if isa chains.
  • Ambiguity between equally specific methods is an error; define the intersection method to fix it.
  • You can add methods to existing functions, including Base ones, for your own types; avoid type piracy.
  • Behavior lives in functions, not in classes, and structs never inherit fields.

Next: make methods work for whole families of types with Parametric Types and Generic Code.