Inheritance in Parametric Types

davibarreira
Tue, 18 Jan 2022 16:00:25 +0000
General Usage

Friends, I have a small conundrum in terms on code design, and some input is more than welcomed.
So, I’m developing a plotting library, and I have a struct called Marker. Now, the code implements different markers, e.g. Circle, Square and so on. So, I have the following struct:

using Parameters
@with_kw mutable struct JMarker{M}
    fillcolor::Union{String, Color}   = "black"
    strokecolor::Union{String, Color} = "black"
    fillopacity::Real = 0.8
    strokewidth::Real = 0
    strokestyle::String = "solid"
    strokeopacity::Real = 0
    mark::M
end

All good. Now, the issue is the following. When creating a mark, I wish the it could “override” the default fields if the mark has them, e.g.:

@with_kw mutable struct Circle
    fillcolor::Union{String, Color}   = "blue"
    radius::Real = 1
end

m = Marker(mark=Circle())

m.fillcolor ### Should be "blue" and not "black".

Of course, the way that I coded this, it doesn’t work. I could simply do m = Marker(mark=Circle(), fillcolor = "blue"), but this does not seem as an elegant solution. Is there a nice/elegant way of doing this?

8 posts - 3 participants