Subtyping vs adding a function to a struct's fields

I suppose you do not find map(x -> x.mass, vector_of_b)? XD

Awesome, @cstjean. I should also say it’s been many months since I’ve looked, so it’s possible that some of your work maintaining it might have fixed some of the issues. Happy to help diagnosing if you ever get to the point where you become concerned about this.

1 Like

Just had a thought if you can guarantee all your box types have the same structure. You could put the box number as a type parameter in a parametric struct definition (defines an iterated union of concrete types). I’m also adding a parameter to make the fields share a floating point type. You can dispatch on the numbered subtypes, and you can just use dot field access instead of interface methods or whatever strategies if you are certain you won’t need to change the structure and fields ever. It’s like moving the separate dispatch argument I suggested earlier into the type parameters for Box, which can be neater, but downsides are needing to make an outer constructor and needing to compile for the different Box{N} separately even when you don’t need separate methods for different N.

struct Box{N,T}
  material::String
  mass::T
  height::T
  length::T
  width::T
end

# fields cannot imply N, so a Box method is not automatically made
# we can write a Box{N} method
# note that Box{N} is abstract: Box{1} === Box{1,T} where T
Box{N}(a,b::T,c::T,d::T,e::T) where {N,T} = Box{N,T}(a,b,c,d,e)

position(b::Box{1}, t) = (t, t^2)
position(b::Box{2}, t) = (t + b.width/2, t + b.height/2)

position(Box{1}("wood", 5.6, 2.0, 124.0, 4.0), 2.5)
position(Box{2}("iron", 54.8, 2.0, 124.0, 4.0), 2.5)

# function that doesn't have separate methods per N
volume(b::Box) = b.height * b.width * b.length