🎓 A1Learner
🔍
0 of 47 lessons completed

Julia Parametric Dispatch Edges

Parametric dispatch edges are the boundary cases where method signatures overlap or share a type. A shared type rule or a more exact method settles which method runs.

A diagonal rule forces one shared type

The same type name appears in both positions. Integers share one type and strings share one type.

mix(x::T, y::T) where T = "one type for both"
println(mix(3, 4))
println(mix("a", "b"))

An exact method wins an overlapping call

Two general methods overlap on two integers. The exact method for two integers wins that call.

showpair(x::Number, y::Int) = "number then int"
showpair(x::Int, y::Number) = "int then number"
showpair(x::Int, y::Int) = "int then int"
println(showpair(3.5, 4))
println(showpair(3, 4.5))
println(showpair(3, 4))

A diagonal rule can still add numbers

The shared type is a number type in both calls. The sums follow the shared type of each call.

both(x::T, y::T) where T<:Number = x + y
println(both(3, 4))
println(both(2.5, 3.5))

Example

showpair(x::Number, y::Int) = "number then int"
showpair(x::Int, y::Number) = "int then number"
showpair(x::Int, y::Int) = "int then int"
both(x::T, y::T) where T<:Number = x + y
println(showpair(3, 4))
println(showpair(3.5, 4))
println(both(3, 4))
println(both(2.5, 3.5))

Key points

  • Overlap: two methods overlap when one call could match both signatures.
  • Ambiguous call: a call that matches two methods with no more exact method to choose.
  • More exact method: a method that matches the overlapping call more closely and wins.
  • Diagonal constraint: a rule written with one type name in two positions that forces both arguments to share that type.
  • Use a diagonal constraint to require two arguments of the same type.

In this example, the exact method wins the call with two integers. The general method wins the call with a decimal and an integer. The diagonal rule then adds two integers and two decimals.

Note

adding the exact overlapping method removes the ambiguity for that call.

Try it Yourself

Edit the code, then press Run.

Running is simulated · JuliaHub

Exercise

Two methods cover (Number, Int) and (Int, Number). Without an (Int, Int) method, which call has no winner?