Dispatching on type alias

I want to create a type alias for the standard array type, i.e.:

const MyArray = Array

and I want to be able to dispatch on this type in a way that is unique for MyArray, e.g.:

function test(::MyArray)
    println("It's mine!")

function test(::Array)
    println("It ain't mine")

Presently this won’t work. MyArray immediately resolves to Array and the compiler doesn’t know about it. So in the above example, the latter definition of test() will always be dispatched.

Is there some kind of work around for what I want to do? I want a type that is an array type in every way and inherits all its standard functions with the exception that I can dispatch to unique functions based on its type.

Because with const MyArray = Array you’re saying MyArray and Array are the same type!

To get what you want, you need to define your own type that wraps an Array and forwards all the AbstractArray methods (which is more annoying than it could be…, see Interfaces · The Julia Language)

Then you can dispatch on it separately.


@Raf Yup, that’s what I was trying to avoid: forwarding all those calls to the inner array isn’t especially elegant and quite annoying!

In the end, I decided it was easier to dispatch on the eltype() rather than the array itself, even if that means having a struct wrapping nothing but a single float value. Semantically this makes more sense for my current purposes (since this float is kind of a type of unit I don’t want simply added other floats) but also the number of float methods I need to forward (in my case) is just a few.

1 Like