Julia Dispatch Ambiguity
Dispatch ambiguity is when a call fits two methods equally well. Julia cannot pick one, so the call fails.
Each overlapping method wins its own clear call
Both methods accept some of the same calls. Each clear call below matches only one method.
f(x::Number, y::Int) = "number first"
f(x::Int, y::Number) = "whole first"
println(f(2.5, 3))
println(f(3, 2.5))An equal call fails and can be caught
The call fits both methods. A try block catches the error and prints a fixed message.
f(x::Number, y::Int) = "number first"
f(x::Int, y::Number) = "whole first"
try
f(1, 2)
catch e
println("no single best method")
endA more specific method removes the clash
A third method fits the call best. Julia picks it and the call succeeds.
f(x::Number, y::Int) = "number first"
f(x::Int, y::Number) = "whole first"
f(x::Int, y::Int) = "both whole"
println(f(1, 2))Example
pick(x::Number, y::Int) = "first form"
pick(x::Int, y::Number) = "second form"
try
pick(1, 2)
catch e
println("no single best method")
end
pick(x::Int, y::Int) = "exact form"
println(pick(1, 2))Key points
- Overlapping methods: two methods can both match the same call.
- Equal match: neither method is more specific than the other for that call.
- Failed call: Julia reports an error instead of guessing a method.
- Safe handling: a try block can catch the error and print a fixed message.
- Fix: add a more specific method for the overlapping call.
In this example, two methods overlap. A try block catches the failed call and prints a fixed message. A third method is then added for the exact call. The final call prints the new result.
Note
an error in Julia stops the script unless a try block catches it.
Try it Yourself
Edit the code, then press Run.
Running is simulated · JuliaHub
Exercise
Two methods exist for f. One takes a Number and an Int. The other takes an Int and a Number. Which call fits both methods equally well?