# InlineDispatch.jl – A simple module to perform dispatch on the value of an expression

**URL:** https://discourse.julialang.org/t/inlinedispatch-jl-a-simple-module-to-perform-dispatch-on-the-value-of-an-expression/102780
**Category:** Package Announcements
**Tags:** exception, dispatch, multiple-dispatch, try-catch
**Created:** [August 14, 2023, 6:41am UTC](https://discourse.julialang.org/t/inlinedispatch-jl-a-simple-module-to-perform-dispatch-on-the-value-of-an-expression/102780 "2023-08-14T06:41:08Z")
**Posts on this page:** 1
**Page:** 1

<div class="post-metadata">

### Author: ![HanD](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/hand/32/213908_2.png) [@HanD](https://discourse.julialang.org/u/HanD)
#### Post date: [August 14, 2023, 6:41am UTC](https://discourse.julialang.org/t/inlinedispatch-jl-a-simple-module-to-perform-dispatch-on-the-value-of-an-expression/102780/1 "2023-08-14T06:41:08Z")

</div>

Based on a [discussion here on Discourse](https://discourse.julialang.org/t/new-syntax-suggestion-catch-with-type-specs/101840), I’m happy to announce a new package called [`InlineDispatch.jl`](https://github.com/dhanak/InlineDispatch.jl) for dispatching on values using anonymous functions.

The following expression:

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

```

performs 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-auto
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!

```

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

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

```

It’s just that! A simple module for a simple task. Happy dispatching!
