How can I make a variable always equal to the result of some calculations?

前端 未结 12 1752
傲寒
傲寒 2021-02-02 05:34

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

12条回答
  •  无人及你
    2021-02-02 06:02

    There are two chief techniques:

    1. 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).

    2. 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.

提交回复
热议问题