🎓 A1Learner
🔍
0 of 48 lessons completed

Julia Value Dispatch

Value dispatch is a method choice based on a value, not only on a type. A value is wrapped in Val, and Julia picks the method for that exact value.

Each wrapped value picks its own method

Each method matches one wrapped value. Each call prints its own result.

mode(::Val{:small}) = "small mode"
mode(::Val{:large}) = "large mode"
println(mode(Val(:small)))
println(mode(Val(:large)))

A general method covers the other values

A general method covers wrapped values with no special method. The first call uses its special method.

mode(::Val{:small}) = "small mode"
mode(x) = "other mode"
println(mode(Val(:small)))
println(mode(Val(:large)))

Wrapped whole numbers can pick a method

Wrapped whole numbers can also pick a method. Each call prints its own level.

level(::Val{1}) = "level one"
level(::Val{2}) = "level two"
println(level(Val(1)))
println(level(Val(2)))

Example

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

Key points

  • Val wrapper: a Val value wraps a plain value so a method can match it.
  • Exact value: a method for one wrapped value runs only for that value.
  • Other values: a different wrapped value needs its own method or a general method.
  • Use Val to pick a method from a setting name.
  • Call form: a call wraps the value in round brackets, and a method heading names the value in braces.

In this example, two methods give prices for two sizes. A general method gives zero for any other size. Three calls print five, nine, and zero.

Note

Val picks by value, and ordinary methods pick by type.

Try it Yourself

Edit the code, then press Run.

Running is simulated · JuliaHub

Exercise

Which call runs the method written for the wrapped value small?