Skip to content
Julia

Despacho múltiplo

Seleciona métodos pelos tipos em tempo de execução de todos os argumentos, não apenas o receptor.

#dispatch#types#oop

Code

julia
# 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)