Best practices for type dispatch?


#1

Say I want to create a function that has two methods, each dispatching on a specific (sub)type:

abstract type AbstractFooBar end

struct Foo <: AbstractFooBar end
struct Bar <: AbstractFooBar end

There are (at least) two ways to do this:

f(::Type{Foo}) = 1
f(::Type{Bar}) = 2

f(Foo) == 1
f(Bar) == 2

and

f(::Foo) = 1
f(::Bar) = 2

f(Foo()) == 1
f(Bar()) == 2

Which is most Julia-like?

Also, are there other options available to me? (Don’t assume that there are only two types; in my real-world case, I will have upwards of 20.)


#2

Duplicate. Here’s my answer.


#3

Gah. Sorry about that, @ChrisRackauckas - I didn’t think to search on singleton type.


#4

All is well.