InlineDispatch.jl

A simple Julia module to perform dispatch on a value of an expression using the `@dispatch` macro.
Author dhanak
Popularity
9 Stars
Updated Last
8 Months Ago
Started In
August 2023

CI codecov Aqua QA

InlineDispatch.jl

A simple module to perform dispatch on the value of an expression using the @dispatch macro.

    @dispatch expr begin
        v::Type1 -> body1...
        v::Type2 -> body2...
    end

Perform a dispatch on the value of expr.

The dispatch uses the anonymous functions in the block as methods, and returns the value of the appropriate body expression. The order of the functions doesn't matter, the most specific match is chosen, as customary with Julian dispatch.

Examples

julia> @dispatch 42 begin
           i::Integer -> "int $i"
           r::Real    -> "real $r"
           ::Nothing  -> "nothing"
       end
"int 42"

julia> @dispatch π begin
           i::Integer -> "int $i"
           r::Real    -> "real $r"
           ::Nothing  -> "nothing"
       end
"real π"

julia> @dispatch "foo" begin
           i::Integer -> "int $i"
           r::Real    -> "real $r"
           ::Nothing  -> "nothing"
       end
ERROR: @dispatch: Unmatched type String! @ REPL[3]:1

It can be particularly useful in try ... catch blocks to handle various types of errors.

julia> try
           do_some_stuff()
       catch exn
           @dispatch exn begin
               e::AssertionError -> println(stderr, "AssertionError: ", e.msg)
               ::InexactError    -> println(stderr, "InexactError")
               _                 -> rethrow()
           end
       end