Skip to content

Instantly share code, notes, and snippets.

@jaantollander
Last active July 25, 2021 07:10
Show Gist options
  • Save jaantollander/5653a0f56b2da35353211c3dd28b419f to your computer and use it in GitHub Desktop.
Save jaantollander/5653a0f56b2da35353211c3dd28b419f to your computer and use it in GitHub Desktop.
Value-based dispatch in Julia language
module ValueBasedDispatch
export MyType, A, B, C, f
abstract type MyType end
struct A <: MyType end
struct B <: MyType end
struct C <: MyType end
f(::Type{A}) = "Dispatch on argument A"
f(::Type{B}) = "Dispatch on argument B"
f(t::Type{T}) where T <:MyType = throw(DomainError("$(t)"))
end

We can dispatch on the value types.

julia> f(A)
"Dispatch on argument A"
julia> f(B)
"Dispatch on argument B"
julia> f(C)
ERROR: DomainError with C:

Third-party code can extend MyType with new type D.

using ValueBasedDispatch

struct D <: MyType end
f(D) = "Dispatch on argument D"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment