🎓 A1Learner
🔍
0 of 48 lessons completed

Julia Dispatch in Practice

Dispatch in practice is using method choice to solve a real small task. The lessons in this course come together in one tidy function set.

Each shape gets its own method

Each shape gets its own method. Each call prints its own area.

struct Square
    side::Int
end
struct Rect
    w::Int
    h::Int
end
area(s::Square) = s.side * s.side
area(r::Rect) = r.w * r.h
println(area(Square(3)))
println(area(Rect(3, 4)))

A setting name picks a price

A setting name picks a price. Each call prints its own price.

cost(::Val{:small}) = 5
cost(::Val{:large}) = 9
println(cost(Val(:small)))
println(cost(Val(:large)))

A check comes before a new call

A check asks about a decimal argument. The count prints the number of methods.

label(x::Int) = "whole"
label(x::String) = "text"
println(hasmethod(label, (Float64,)))
println(length(methods(label)))

Example

cost(::Val{:small}) = 5
cost(::Val{:large}) = 9
add(x::T, y::T) where T = x + y
println(cost(Val(:small)))
println(add(cost(Val(:small)), cost(Val(:large))))
println(length(methods(cost)))
try
    add(2, "a")
catch e
    println("types must match")
end

Key points

  • Interface first: decide the calls a function must support before writing its methods.
  • Special cases: give each special case its own method.
  • General cover: a broad method handles every case left over.
  • Value choice: use Val when the choice depends on a named setting.
  • Shared type: use a where method when two arguments must share one type.
  • Check: count methods and test each call before trusting the set.

In this example, two size methods give prices. A shared-type method adds the two prices. The count prints two. A mixed call fails, and a try block prints a fixed message.

Note

a caught error with a fixed message keeps a demo tidy when a call has no match.

Try it Yourself

Edit the code, then press Run.

Running is simulated · JuliaHub

Exercise

What is the first step when designing a function set?