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
b = 3 * a
julia> s = S(a=5)
julia> s.a = 10
Would it be possible to make b automatically value
3 * 10 = 30 ?
Generally the better way to do this is to make
b be a property overload. i.e.
mutable struct S
Base.propertynames(::S) = (:a, :b)
function Base.getproperty(s::S, p::Symbol)
if p == :b
return 3 * getfield(s, :a)
return getfield(s, p)
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.