Automatic update of the values of a structure

Hello :grin:,
I would like to know if it is possible to automatically update the parameters of a strcutre when it is modified. For example, in the following example, the value of b is not updated when a changes:

julia> Base.@kwdef mutable struct S
                  a
                  b = 3 * a
                  end
S

julia> s = S(a=5)
S(5, 15)

julia> s.a = 10
10

julia> s
S(10, 15)

Would it be possible to make b automatically value 3 * 10 = 30 ?

Thanks ! :grin:
fdekerm

Generally the better way to do this is to make b be a property overload. i.e.

mutable struct S
    a
end

Base.propertynames(::S) = (:a, :b)
function Base.getproperty(s::S, p::Symbol)
    if p == :b
        return 3 * getfield(s, :a)
    end
    return getfield(s, p)
end
3 Likes

Wow great thanks a lot!

The above-mentioned method of Base.getproperty overloading is best.

The alternative would be to make a specialized method for Base.setproperty!(s::S, field::Symbol, value), but that will be more complicated and easier to break.

1 Like