Skip to content

Instantly share code, notes, and snippets.

@jaantollander
Last active August 31, 2023 07:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jaantollander/f88c449814631b2120e49b363ec47c06 to your computer and use it in GitHub Desktop.
Save jaantollander/f88c449814631b2120e49b363ec47c06 to your computer and use it in GitHub Desktop.
Multiple dispatch in Julia language
module MultipleDispatch
export A, A1, A2, f
# Abstract type
abstract type A end
# Concrete types
struct A1 <: A end
struct A2 <: A end
# Methods: Single dispatch
f(::Type{A1}) = "A1"
f(::Type{A2}) = "A2"
# Methods: Multiple dispatch
f(a1::Type{<:A}, a2::Type{<:A}) = f(a1) * "×" * f(a2)
f(a::Type{<:A}...) = join(f.(a), "×")
end

Single dispatch

julia> using .MultipleDispatch
julia> f(A1)
"A1"
julia> f(A2)
"A2"

Multiple dispatch

julia> f(A1, A1)
"A1×A1"
julia> f(A1, A2)
"A1×A2"
julia> f(A2, A1)
"A2×A1"
julia> f(A2, A2)
"A2×A2"

Extending

struct A3 <: A end
MultipleDispatch.f(::Type{A3}) = "A3"
f(A1, A2, A3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment