Multiple dispatch in Julia
One function name; the method is chosen by every argument's type.
# One function name, one method per argument signature: dispatch
# picks by the types of every argument, not just the first.
describe(m::Real) = "magnitude $m"
describe(name::String) = "target $name"
describe(name::String, m::Real) = "$name at magnitude $m"
println(describe(4.2))
println(describe("Altair"))
println(describe("Altair", 0.76))
# methods() shows the table dispatch chooses from.
println(length(methods(describe)), " methods defined")
How it works
- Three
describemethods differ only in signatures. - Calls route by type: a Real, a String, or the pair.
methods(describe)lists the table dispatch chooses from.
Keywords and builtins used here
RealString
The run, in numbers
- Lines
- 12
- Characters to type
- 450
- Tokens
- 82
- Three-star pace
- 70 tpm
At the three-star pace of 70 tokens a minute, this run takes about 70 seconds.
Step 2 of 3 in Functions, step 8 of 27 in Language basics.