[ANN] InstanceDispatch.jl: Dispatch-on-value with anyting that defines a `Base.instances` method

klafyvel
Fri, 18 Jul 2025 08:13:57 +0000
Package Announcements

Hi there,
I just started the registration process for InstanceDispatch.jl, a single-macro package that writes for you a method that dispatches on methods with value-type from a type that defines a Base.instances method (typically an @enum). Say you have a function that behaves differently depending on a flag that has been passed to it (typically a finite state machine). For example

@enum GreetEnum Hello Goodbye

function greet(::Val{Hello}, who)
    return "Hello " * who
end
function greet(::Val{Goodbye}, who)
    return "Goodbye " * who
end

In your state machine you would like to store the flag as an instance of the enum, but then simply calling greet(Val(state), somename) is not type stable. This package automates the tedious task of writing and maintaining the following method:

function greet(e::GreetEnum, who)
    if e == Hello
        return greet(Val(Hello), who)
    elseif e == Goodbye
        return greet(Val(Goodbye), who)
    else
    end
end

Instead you can simply write:

@instancedispatch greet(::GreetEnum, who)

There’s also the possibility of dispatching on multiple enums, you can check the documentation!

8 posts - 4 participants