In math, if z = x + y / 2
, then z
will always change whenever we replace the value of x
and y
. Can we do that in programming
There are two chief techniques:
Deferred calculation - instead of z
being a simple variable, make it a function which calculates the value on demand (see other answers for examples). This can be source-code transparent if z
is some proxy object with implicit conversion to the required type (as in Aconcagua's answer).
Explicit notification of changes. This requires x
and y
to be observable types; when either changes value, then z
updates itself (and notifies its observers if applicable).
The first version is usually preferred, but the second may be more appropriate if you need z
to be an observable type.