Skip to content
Julia

Multiple Dispatch

Select methods by the runtime types of all arguments, not just the receiver.

By EZ4Code Team
dispatchtypesoop

Code

# Methods are dispatched on ALL argument types, not just 'this'
struct Point
    x::Float64
    y::Float64
end

# Different methods of the same function for different type combos
distance(p::Point, q::Point) = hypot(p.x - q.x, p.y - q.y)
distance(p::Point, origin::Tuple{0,0}) = hypot(p.x, p.y)

# Add methods to existing functions (e.g. Base.:+)
Base.:+(p::Point, q::Point) = Point(p.x + q.x, p.y + q.y)
Base.show(io::IO, p::Point) = print(io, "($(p.x), $(p.y))")

p = Point(1.0, 2.0)
q = Point(3.0, 4.0)
println(p + q)              # (4.0, 6.0)
println(distance(p, q))     # 2.828...

# Inspect methods
methods(distance)

Explanation

Julia uses multiple dispatch: the compiler picks the most specific method matching the runtime types of every argument. This is more general than single dispatch (C++/Java virtual methods) and lets you add methods to functions you don't own — including Base.:+. The result is that user-defined types can be as fast and ergonomic as built-ins, which is why Julia libraries compose so well.

More Julia Snippets