Making broadcast work for own type



If I have my own type, which can be indexed like an array, and has a length. How can I get broadcast to work with it as an array-like type instead of a scalar? I can only find useage guides in the language manual for vectorised ops and broadcasting, nothing about extending the broadcast method to new types.


I’m a little fuzzy on exactly what you are trying to do, but you have several options.

First of all, as I understand it, broadcast methods are intended for cases where there is an actual underlying loop. If your method is abstract, and does not involve a loop, it is better to write dedicated, undotted, methods. Most of the time the right thing to do is only to overload undotted methods for individual objects, and use the automatic promotion provided by broadcast rather than overloading it.

That said, if you want to actually overload a dotted operation, you should do

broadcast(::typeof(op), arg) = # here is your loop over elements of arg

With this method defined, you can then do op.(arg) and it will execute your method.


The easiest way would be to make your type <: AbstractArray and define size and getindex. That should enable broadcasting to just work. Or is your type not sufficiently array-like for it to be an AbstractArray?


My type does many things an array (actually more like a vector) does, insofar as indexing and having length and eltype and so on. So it has those behaviours, but also a lot more that means it would not be neatly bike-shedded under AbstractArray. I’d like to know what one would do to allow broadcasting (vectorised dot operations) in that situation. Kind-of how say a string has many array (of char) like properties, but crucially it is not an array in the type hierarchy (and also does not support vectorised dot operations AFAIK).


Even though the code changed a bit, most of this is still relevant: