https://github.com/dhanak/inlinedispatch.jl
A simple Julia module to perform dispatch on a value of an expression using the `@dispatch` macro.
https://github.com/dhanak/inlinedispatch.jl
dispatch error-handling julia try-catch
Last synced: 9 months ago
JSON representation
A simple Julia module to perform dispatch on a value of an expression using the `@dispatch` macro.
- Host: GitHub
- URL: https://github.com/dhanak/inlinedispatch.jl
- Owner: dhanak
- License: mit
- Created: 2023-08-04T08:45:58.000Z (over 2 years ago)
- Default Branch: master
- Last Pushed: 2024-02-06T15:24:13.000Z (almost 2 years ago)
- Last Synced: 2025-04-08T12:12:08.255Z (10 months ago)
- Topics: dispatch, error-handling, julia, try-catch
- Language: Julia
- Homepage:
- Size: 12.7 KB
- Stars: 9
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
[](https://github.com/dhanak/InlineDispatch.jl/actions/workflows/CI.yml)
[](https://codecov.io/gh/dhanak/InlineDispatch.jl)
[](https://github.com/JuliaTesting/Aqua.jl)
# InlineDispatch.jl
A simple module to perform dispatch on the value of an expression using the
`@dispatch` macro.
```julia
@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
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
julia> try
do_some_stuff()
catch exn
@dispatch exn begin
e::AssertionError -> println(stderr, "AssertionError: ", e.msg)
::InexactError -> println(stderr, "InexactError")
_ -> rethrow()
end
end
```