JULIA / CHAPTER 09
Dispatch intersections and method ambiguity
AdvancedResolve overlapping methods with an explicit shared case.
By the end of this chapter
- Identify incomparable applicable methods
- Define a method at an overlap
- Keep method extensions within types or functions you own
The idea
Multiple dispatch chooses the most specific applicable method using all argument types. Two methods can overlap without either being more specific overall: one can constrain the first argument more tightly while another constrains the second. Calling their shared region is then ambiguous unless another method describes that intersection. Trace the argument tuple rather than assuming the most recently defined method wins.
A clear repair is often an explicit method for the overlapping case, with behavior that preserves the API’s meaning. Avoid adding unrelated broad methods just to silence one ambiguity. Extending a function you do not own for types you also do not own can affect code elsewhere, so place extensions at intentional ownership boundaries. Test ordinary calls, boundary combinations, and the exact intersection separately.
classify(x::Integer, y::Number) = "left"
classify(x::Number, y::Integer) = "right"
classify(x::Integer, y::Integer) = "both"
println(classify(1, 2))
println(classify(1, 2.0))both left
The Integer/Integer method resolves the overlap and is more specific for the first call. Only the first broad method fits the second call.
Try it yourself
Design three combine methods with two overlapping numeric signatures and an explicit intersection policy.
Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.
CHECK YOUR UNDERSTANDING