Julia Methods & Multiple Dispatch
In Julia, a function is a name such as area or +. A method is one concrete implementation of that function for particular argument types. A function can have many methods, and when you call it, Julia picks the most specific method that matches the types of all the arguments. This is multiple dispatch, and it is the central design idea of the language.
describe(x) = "something"
describe(x::Number) = "a number"
describe(x::Integer) = "an integer"
describe(x::AbstractString) = "a string"
for v in (3, 2.5, "hi", [1])
println(repr(v), " is ", describe(v))
end
println(length(methods(describe)), " methods")3 is an integer
2.5 is a number
"hi" is a string
[1] is something
4 methods
3 matches both Number and Integer, and Julia chooses Integer because it's more specific. Unannotated arguments mean ::Any, the least specific type.
Dispatch on all arguments
Object-oriented languages choose a method based on one special object (obj.method(arg)). Julia considers every argument equally, which models interactions between types naturally:
abstract type Pet end
struct Dog <: Pet; name::String end
struct Cat <: Pet; name::String end
meet(a::Dog, b::Dog) = "sniff"
meet(a::Dog, b::Cat) = "chase"
meet(a::Cat, b::Dog) = "hiss"
meet(a::Cat, b::Cat) = "ignore"
encounter(a::Pet, b::Pet) = println(a.name, " meets ", b.name, ": ", meet(a, b))
rex, tom, kit = Dog("Rex"), Cat("Tom"), Cat("Kit")
encounter(rex, tom)
encounter(tom, rex)
encounter(tom, kit)
encounter(rex, rex)Rex meets Tom: chase
Tom meets Rex: hiss
Tom meets Kit: ignore
Rex meets Rex: sniff
encounter is written once for any Pet. Inside it, meet(a, b) dispatches on the runtime types of both pets.
Extending existing functions
You can add methods to functions from Base, such as +, show, length or isless, for your own types. Your types then work with all the generic code built on those functions:
struct Money
cents::Int
end
Base.:+(a::Money, b::Money) = Money(a.cents + b.cents)
Base.:*(a::Money, k::Real) = Money(round(Int, a.cents * k))
Base.:*(k::Real, a::Money) = a * k
Base.isless(a::Money, b::Money) = a.cents < b.cents
Base.show(io::IO, m::Money) = print(io, "\quot;, m.cents ÷ 100, ".", lpad(m.cents % 100, 2, '0'))
Base.zero(::Type{Money}) = Money(0)
wallet = [Money(1250), Money(399), Money(5000)]
println(wallet[1] + wallet[2])
println(3 * Money(199))
println(sum(wallet))
println(maximum(wallet), " ", sort(wallet))$16.49
$5.97
$66.49
$50.00 Money[$3.99, $12.50, $50.00]
sum, maximum and sort were never written for Money, yet they work, because they're built on +, zero and isless. This kind of composability is what makes the Julia ecosystem fit together so well.
Ambiguities
If two methods are equally specific for a call, Julia can't choose and reports an ambiguity. Fix it by adding a method for the overlapping case:
combine(a::Int, b) = "int first"
combine(a, b::Int) = "int second"
try
combine(1, 2)
catch e
println(typeof(e))
end
combine(a::Int, b::Int) = "both ints"
println(combine(1, 2), " / ", combine(1, "x"), " / ", combine("x", 1))MethodError
both ints / int first / int second
Inspecting dispatch
methods(f) lists the methods of f, hasmethod checks whether a call would match, and which (from InteractiveUtils, loaded automatically in the REPL) shows the method a call would use:
area(r::Real) = π * r^2
area(w::Real, h::Real) = w * h
println(length(methods(area)))
println(hasmethod(area, Tuple{Int}), " ", hasmethod(area, Tuple{String}))
println(applicable(area, 2, 3), " ", area(2, 3))
try
area("big")
catch e
msg = sprint(showerror, e)
println(first(split(msg, '\n'))) # just the first line
end2
true false
true 6
MethodError: no method matching area(::String)
A MethodError with "no method matching" means no method accepts that combination of argument types — one of the most common errors you'll read in Julia.
Test yourself
With methods f(x::Number) and f(x::Integer), which runs for f(5)?
- f(x::Number)
- f(x::Integer)
- Both
- Neither: it's ambiguous
What does multiple dispatch base its choice on?
- The type of the first argument only
- The types of all arguments
- The order methods were defined in
- The function's return type
How do you make + work for your own type Vec2?
- Override it inside the struct
- Define
Base.:+(a::Vec2, b::Vec2) = ... - Use operator Vec2.+
- It is impossible