🎓 A1Learner
🔍
0 of 47 lessons completed

Julia Singleton Types

Singleton types are types that carry one single value at the type level. Dispatch can then choose a method from that value alone.

A symbol value picks the method

Each symbol carries its own method choice. The fast symbol and the slow symbol give different answers.

mode(::Val{:fast}) = "fast path"
mode(::Val{:slow}) = "slow path"
println(mode(Val(:fast)))
println(mode(Val(:slow)))

A true or false value picks the method

The boolean value is carried at the type level. True gives one answer and false gives the other.

flag(::Val{true}) = "on"
flag(::Val{false}) = "off"
println(flag(Val(true)))
println(flag(Val(false)))

An integer value picks the factor

The integer value is part of the method choice. Each value multiplies by its own factor.

scale(::Val{2}, x) = x * 2
scale(::Val{3}, x) = x * 3
println(scale(Val(2), 10))
println(scale(Val(3), 10))

Example

work(::Val{:fast}) = "fast work"
work(::Val{:slow}) = "slow work"
enabled(::Val{true}) = "enabled"
enabled(::Val{false}) = "disabled"
println(work(Val(:fast)))
println(enabled(Val(true)))
println(work(Val(:slow)))
println(enabled(Val(false)))

Key points

  • Singleton type: a type that carries one single value at the type level.
  • Symbol dispatch: dispatch that chooses a method from a symbol value carried at the type level.
  • Boolean dispatch: dispatch that chooses a method from a true or false value carried at the type level.
  • Use a singleton value to pick a method without adding a run-time check in the body.
  • Call form: passing Val with a value puts that value into the type of the argument.

In this example, work picks a method from a symbol value and enabled picks a method from a boolean value. The four calls show the fast and slow work choices and the enabled and disabled choices.

Note

a singleton type has only one value, so the choice is fixed when the method is chosen.

Try it Yourself

Edit the code, then press Run.

Running is simulated · JuliaHub

Exercise

What does f(Val(:a)) let dispatch choose on?