Best way to dispatch on type field

I have a struct like this

abstract Material

mutable struct Element
   mat::Material
   data::Data
   ...
end

and an overloaded method update! that updates the struct based on concrete types of Material.
Functions like these work ok:

function update!(ele::Element, mat::Material1, options::Options)
function update!(ele::Element, mat::Material2, options::Options)
where Material1<:Material and Material2<:Material.

These functions are then called as:
update!(ele, ele.mat, options)

but seems redundant and not very clear for another programmer that would expect something like update!(ele, options) but in this case multiple dispatch will not work because Element is not polymorphic.

Of course I could make Element<:Material but it is not the case. I need concrete instances of Element because the mat field is assigned in a later stage.

Any suggestions?

Just make a small function

update!(ele::Element, options::Options) = update!(ele,ele.mat,options)

and then update!(ele,options) will work for the outer API.

Or strictly type the fields of Element using a type parameter and dispatch on the type parameter. You should be doing this anyways for performance, otherwise every update! like this will have a dynamic dispatch. Depending on the application, that could very well make the computation take much longer if update! is a quick and repeated calculation.

1 Like